@cline/core 0.0.46 → 0.0.47-nightly.1781493618
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ClineCore.d.ts +2 -0
- package/dist/cline-core/types.d.ts +6 -0
- package/dist/extensions/tools/executors/bash.d.ts +16 -2
- package/dist/extensions/tools/executors/output-limits.d.ts +25 -0
- package/dist/extensions/tools/helpers.d.ts +13 -0
- package/dist/hub/client/index.d.ts +2 -1
- package/dist/hub/daemon/entry.js +201 -192
- package/dist/hub/daemon/index.d.ts +6 -2
- package/dist/hub/daemon/start-shared-server.d.ts +4 -4
- package/dist/hub/discovery/index.d.ts +23 -1
- package/dist/hub/discovery/workspace.d.ts +1 -0
- package/dist/hub/index.js +200 -191
- package/dist/hub/server/hub-websocket-server.d.ts +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +200 -191
- package/dist/runtime/host/local-runtime-host.d.ts +1 -0
- package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +0 -1
- package/dist/services/feature-flags/FeatureFlagsService.d.ts +49 -0
- package/dist/services/feature-flags/index.d.ts +2 -0
- package/dist/services/feature-flags/posthog.d.ts +24 -0
- package/dist/services/feature-flags/posthog.js +1 -0
- package/dist/services/feature-flags/providers.d.ts +7 -0
- package/dist/services/providers/local-provider-service.d.ts +4 -1
- package/dist/services/storage/provider-settings-manager.d.ts +7 -2
- package/dist/services/telemetry/core-events.d.ts +3 -0
- package/dist/services/telemetry/index.d.ts +1 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/session/services/message-builder.d.ts +16 -2
- package/dist/types.d.ts +3 -1
- package/package.json +18 -5
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)}function
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`)}function
|
|
5
|
-
`,"utf8"),X??{}}function NJ(f={}){return Yf(f).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function V1(f,$={}){let J=Yf($);for(let Q of J)await f.registerServer(Q);return J}var MJ,MA,TZ,H_,X_,A_,Y_,V_,B_,NA,K_,P_,G_,F_;var K5=h$(()=>{MJ=C.record(C.string(),C.string()),MA=C.record(C.string(),C.unknown()),TZ=C.object({clientInformation:C.record(C.string(),C.unknown()).optional(),tokens:C.record(C.string(),C.unknown()).optional(),codeVerifier:C.string().optional(),discoveryState:C.record(C.string(),C.unknown()).optional(),redirectUrl:C.string().url().optional(),lastError:C.string().optional(),lastAuthenticatedAt:C.number().int().positive().optional()}).strip(),H_=C.object({type:C.literal("stdio"),command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:MJ.optional()}),X_=C.object({type:C.literal("sse"),url:C.string().url(),headers:MJ.optional()}),A_=C.object({type:C.literal("streamableHttp"),url:C.string().url(),headers:MJ.optional()}),Y_=C.discriminatedUnion("type",[H_,X_,A_]),V_=C.object({transport:Y_,disabled:C.boolean().optional(),metadata:MA.optional(),oauth:TZ.optional()}),B_=C.enum(["stdio","sse","http","streamableHttp"]).optional(),NA=C.object({type:C.enum(["stdio","sse","streamableHttp"]).optional(),transportType:B_,disabled:C.boolean().optional(),metadata:MA.optional(),oauth:TZ.optional()});K_=NA.extend({command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:MJ.optional()}).superRefine((f,$)=>{let J=f.type??_Z(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,oauth:f.oauth})),P_=NA.extend({url:C.string().url(),headers:MJ.optional()}).superRefine((f,$)=>{let J=f.type??_Z(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??_Z(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata,oauth:f.oauth}}),G_=C.union([V_,K_,P_]),F_=C.object({mcpServers:C.record(C.string(),G_)}).passthrough()});import{existsSync as PM,mkdirSync as GM,readFileSync as FM,writeFileSync as UM}from"node:fs";import{resolve as RM}from"node:path";import{resolveSessionDataDir as DM}from"@cline/shared/storage";import{nanoid as LM}from"nanoid";import*as _M from"node-machine-id";function _1(f){let $=f?.trim();if($)return $;let J=zM();if(J)return J;return MM()}function TM(){let f=_M;return f.machineIdSync??f.default?.machineIdSync}function zM(){try{let f=TM();if(!f)return;return f().trim()||void 0}catch{return}}function MM(){let f=DM(),$=RM(f,OM);try{if(PM($)){let Q=FM($,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${LM()}`;try{GM(f,{recursive:!0}),UM($,J,"utf8")}catch{}return J}var OM="machine-id";var x5=()=>{};class Z4{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,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get(f);if(!W)W=this.meter.createCounter(f,Q?{description:Q}:void 0),this.counters.set(f,W);W.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get(f);if(!W)W=this.meter.createHistogram(f,Q?{description:Q}:void 0),this.histograms.set(f,W);W.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),H=this.gaugeValues.get(f);if($===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set(f,X);if(!this.gauges.has(f)){let A=this.meter.createObservableGauge(f,Q?{description:Q}:void 0);A.addCallback((Y)=>{for(let V of this.snapshotGaugeSeries(f))Y.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set(f,A)}X.set(j,{value:$,attributes:W})}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 Q=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:Q})}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,Q=0){if(!f)return{};let Z={},W=100,j=10;for(let[H,X]of Object.entries(f)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let A=$?`${$}.${H}`:H;if(X===null||X===void 0){Z[A]=String(X);continue}if(Array.isArray(X)){let Y=X.length>W?X.slice(0,W):X;try{Z[A]=JSON.stringify(Y)}catch{Z[A]="[UnserializableArray]"}if(X.length>W)Z[`${A}_truncated`]=!0,Z[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[A]=X.toISOString();continue}if(X instanceof Error){Z[A]=X.message;continue}if(J.has(X)){Z[A]="[Circular]";continue}if(Q>=j){Z[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,A,J,Q+1));continue}if(bN(X)){Z[A]=X;continue}try{Z[A]=JSON.stringify(X)}catch{Z[A]=String(X)}}return Z}}function bN(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class W4{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,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:Q,required:Z===!0})}recordHistogram(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:Q,required:Z===!0})}recordGauge(f,$,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class v2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new W4({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 Q of this.adapters)Q.emitRequired(f,J)}recordCounter(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter(f,$,W,Q,Z)}recordHistogram(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram(f,$,W,Q,Z)}recordGauge(f,$,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge(f,$,W,Q,Z)}async flush(){await Promise.all(this.adapters.map((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 EW=()=>{};import{metrics as kN,trace as IN}from"@opentelemetry/api";import{logs as xN}from"@opentelemetry/api-logs";import{OTLPLogExporter as mN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as gN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as vN}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as cN}from"@opentelemetry/resources";import{BatchLogRecordProcessor as uN,ConsoleLogRecordExporter as dN,LoggerProvider as lN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as pN,MeterProvider as rN,PeriodicExportingMetricReader as gV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as iN,ConsoleSpanExporter as nN,SimpleSpanProcessor as aN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as tN}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as sN,ATTR_SERVICE_VERSION as oN}from"@opentelemetry/semantic-conventions";class vV{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 c2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=cN({[sN]:f.serviceName??"cline",...f.serviceVersion?{[oN]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)kN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)xN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return IN.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new Z4({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new v2({...f,adapters:[$],distinctId:_1(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 $=hW(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=$.map((W)=>$q(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new rN({resource:f,readers:Z})}createTracerProvider(f){let $=hW(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of $){let j=fq(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new tN({resource:f,spanProcessors:Z})}createLoggerProvider(f){let $=hW(this.options.logsExporter);if($.length===0)return null;let J=$.map((Q)=>{let Z=eN(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new uN(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new lN({resource:f,processors:J})}}function j4(f){let $=new c2(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 nf(f){if(G6())return{telemetry:new vV(f)};if(f.enabled!==!0)return{telemetry:new v2({...f,distinctId:_1(f.distinctId)})};return j4(f)}function u2(f){let{telemetry:$,provider:J}=nf(f);return{telemetry:$,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function hW(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function eN(f,$){if(f==="console")return new dN;if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/logs");return new mN({url:J,headers:$.headers})}function fq(f,$){if(f==="console")return new aN(new nN);if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/traces");return new iN(new vN({url:J,headers:$.headers}))}function $q(f,$){if(f==="console")return new gV({exporter:new pN,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/metrics");return new gV({exporter:new gN({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function bW(f,$){let J=new URL(f),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith($)?Q:`${Q}${$}`,J.toString()}var r5=h$(()=>{Af();x5();EW()});var cB={};q(cB,{createOpenTelemetryTelemetryService:()=>j4,createConfiguredTelemetryService:()=>nf,createConfiguredTelemetryHandle:()=>u2,OpenTelemetryProvider:()=>c2,OpenTelemetryAdapter:()=>Z4});var f7=h$(()=>{r5()});import{AgentRuntimeAbortError as CS}from"@cline/agents";import{initVcr as SS}from"@cline/shared";import{normalizeProviderId as qS}from"@cline/llms";var vK={};q(vK,{LocalRuntimeHost:()=>Df});import{readdirSync as RS}from"node:fs";import{homedir as DS}from"node:os";import{isAbsolute as LS,join as J3,resolve as Q3}from"node:path";import{captureSdkError as C1,createSessionId as _S,isLikelyAuthError as OS,normalizeUserInput as TS}from"@cline/shared";import{setHomeDirIfUnset as zS}from"@cline/shared/storage";var u3={};q(u3,{saveProviderOAuthCredentials:()=>I$,resolveProviderApiKeyFromSettings:()=>d9,loginAndSaveProviderOAuthCredentials:()=>X8,isOAuthProvider:()=>k$,getProviderOAuthCredentialsFromSettings:()=>A8,getProviderAuthStorageId:()=>u9,getProviderAuthHandler:()=>V0,getPersistedProviderApiKey:()=>a4,formatProviderOAuthApiKey:()=>l9});import{getClineEnvironmentConfig as c3}from"@cline/shared";_0();var z3={};q(z3,{startClineDeviceAuth:()=>x9,refreshClineToken:()=>c4,loginClineOAuth:()=>$8,getValidClineCredentials:()=>J8,completeClineDeviceAuth:()=>m9});import{getClineEnvironmentConfig as E9}from"@cline/shared";var G3={};q(G3,{startLocalOAuthServer:()=>e0});function jP(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function e0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",Q=f.timeoutMs??300000,Z=f.successHtml??HP,W=jP(),j=!1,H=null,X=null,A=null,Y=(K)=>{if(j)return;j=!0,W.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=A;if(A=null,X)X.close(),X=null;if(K!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),Y(null)},Q),W.promise};for(let K of f.ports){let P=$.createServer((G,F)=>{try{let U=new URL(G.url||"",`http://${J}:${K}`);if(U.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let O={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(O.error){F.statusCode=400,F.end(`Authentication failed: ${O.error}`),V(),Y(O);return}if(!O.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&O.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(Z),V(),Y(O)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((G)=>{let F=(U)=>{P.off("error",F),G({bound:!1,error:U})};P.once("error",F),P.listen(K,J,()=>{P.off("error",F),X=P,G({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){A=K;let G=`http://${J}:${K}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:K,callbackUrl:G})).catch(()=>{});return{callbackUrl:G,waitForCallback:B,cancelWait:()=>{V(),Y(null)},close:()=>{V(),Y(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var HP=`<!DOCTYPE html>
|
|
1
|
+
import{createRequire as uG}from"node:module";var{defineProperty:r9,getOwnPropertyNames:mG}=Object;var w3=Object.prototype.hasOwnProperty;function y3($){return this[$]}var T=($,f,J)=>{var Q=mG(f);for(let Z of Q)if(!w3.call($,Z)&&Z!=="default")r9($,Z,{get:y3.bind(f,Z),enumerable:!0});if(J){for(let Z of Q)if(!w3.call(J,Z)&&Z!=="default")r9(J,Z,{get:y3.bind(f,Z),enumerable:!0});return J}};var vG=($)=>$;function cG($,f){this[$]=vG.bind(null,f)}var w=($,f)=>{for(var J in f)r9($,J,{get:f[J],enumerable:!0,configurable:!0,set:cG.bind(f,J)})};var h$=($,f)=>()=>($&&(f=$($=0)),f);var S3=uG(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as dG}from"@cline/shared";function r($,f,J){$?.capture({event:f,properties:J})}function y6($){if(!$)return;return $.substring(0,lG)}function pG($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function rG($){return typeof $==="string"?$:$.message}function C3($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function E3($){r($,x.CLIENT.EXTENSION_ACTIVATED)}function S6($,f){let J=[...f.vcs_types],Q={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:C3(J,new Set(["git"])),has_mercurial:C3(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)Q.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)Q.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)Q.is_remote_workspace=f.is_remote_workspace;r($,x.WORKSPACE.INITIALIZED,Q)}function C6($,f,J){r($,x.WORKSPACE.INIT_ERROR,{error_type:pG(f),error_message:y6(rG(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function h3($,f){r($,x.WORKSPACE.PATH_RESOLVED,{...f})}function N1($,f){r($,x.USER.AUTH_STARTED,{provider:f})}function q1($,f){r($,x.USER.AUTH_SUCCEEDED,{provider:f})}function w1($,f,J){r($,x.USER.AUTH_FAILED,{provider:f,errorMessage:y6(J)})}function o1($,f,J){r($,x.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function b3($,f){r($,x.USER.PROVIDER_CONFIGURED,{provider:f})}function k3($,f){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,f)}function y1($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function E6($,f){r($,x.TASK.CREATED,f)}function h6($,f){r($,x.TASK.RESTARTED,f)}function X8($,f){r($,x.TASK.COMPLETED,f)}function xf($,f){r($,x.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function b6($,f){r($,x.TASK.TOKEN_USAGE,f)}function k6($,f,J){r($,x.TASK.MODE_SWITCH,{ulid:f,mode:J})}function I6($,f){r($,x.TASK.TOOL_USED,f)}function x6($,f){r($,x.TASK.SKILL_USED,f)}function g6($,f){r($,x.TASK.DIFF_EDIT_FAILED,f)}function Y8($,f){r($,x.TASK.PROVIDER_API_ERROR,{...f,errorMessage:y6(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function I3($,f){r($,x.SDK.TOOL_TIMEOUT,iG(f))}function iG($){let f={};for(let[J,Q]of Object.entries($))if(Q!==void 0)f[J]=Q;return f}function m6($,f,J){r($,x.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function v6($,f,J,Q){r($,x.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:y6(Q),timestamp:new Date().toISOString()})}function c6($,f,J,Q,Z){r($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function e1($,f){r($,x.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function u6($,f){r($,x.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function V8($,f){r($,f.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function d6($,f,J,Q){r($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}function l6($,f){r($,x.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function p6($,f){r($,x.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var lG=500,x;var L0=h$(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:dG,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});var wX={};w(wX,{normalizeUserMessage:()=>oD,buildInitialUserContent:()=>tD});async function tD($,f,J,Q){let Z=eD(f),W=await fR(J,Q);if(Z.length===0&&!W)return $;let j=[{type:"text",text:$},...Z];if(W)j.push(...W);return j}function oD($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let Q of f)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
|
|
2
|
+
`)}function eD($){if(!$||$.length===0)return[];let f=[];for(let J of $){let Q=$R(J);if(Q)f.push(Q)}return f}function $R($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let Q=J[1],Z=J[2];if(!Q||!Z)return;return{type:"image",mediaType:Q,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function fR($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let X=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${X}`}}}));if(Q.length===0)return;return Q}import{mkdirSync as nR,readFileSync as aR,statSync as sR,writeFileSync as tR}from"node:fs";import{dirname as oR}from"node:path";import{resolveGlobalSettingsPath as PY}from"@cline/shared/storage";import{z as j2}from"zod";function OJ(){return e8.parse({})}function eR(){MJ=void 0}function $U($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function fU($){let f;try{f=aR($,"utf8")}catch{return OJ()}try{let J=e8.safeParse(JSON.parse(f));return J.success?J.data:OJ()}catch{return OJ()}}function JU(){let $=PY(),f=sR($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,Q=f?.size??0,Z=MJ;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===Q)return Z;let W=$U(f?fU($):OJ());return MJ={path:$,mtimeMs:J,size:Q,value:W},MJ}function O0(){return JU().value}function x1($,f={}){let J=PY(),Q=O0();nR(oR(J),{recursive:!0});let Z=e8.parse($);if(!Q.telemetryOptOut&&Z.telemetryOptOut)k3(f.telemetry);tR(J,`${JSON.stringify(Z,null,2)}
|
|
3
|
+
`,"utf8"),eR()}function TJ(){return O0().telemetryOptOut}function DY($,f={}){x1({...O0(),telemetryOptOut:$},f)}function RY(){return O0().autoUpdateEnabled}function UY($,f={}){x1({...O0(),autoUpdateEnabled:$},f)}function B1($){return new Set($??O0().disabledTools??[])}function $4($){return new Set($??O0().disabledPlugins??[])}function zY($){return B1().has($)}function NJ($){let f=O0(),J=new Set(f.disabledTools??[]),Q=J.has($);if(Q)J.delete($);else J.add($);return x1({...f,disabledTools:[...J]}),!Q}function fZ($,f){let J=[...new Set($.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=O0(),Z=B1(Q.disabledTools);for(let W of J)if(f)Z.add(W);else Z.delete(W);x1({...Q,disabledTools:[...Z]})}function LY($,f){return fZ([$],f),f}function _Y($){return $4().has($)}function OY($,f){let J=$.trim();if(!J)return;let Q=O0(),Z=$4(Q.disabledPlugins);if(f)Z.add(J);else Z.delete(J);x1({...Q,disabledPlugins:[...Z]})}function qJ($,f){let J=$4(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q))}function s$($,f){let J=B1(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q.name))}function wJ($,f){if(!$||$.length===0)return $;let J=B1(f);if(J.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var FY,e8,MJ;var H1=h$(()=>{L0();FY=j2.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,j2.array(j2.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,Q)=>J.localeCompare(Q));return f.length>0?f:void 0}),e8=j2.object({telemetryOptOut:j2.boolean().default(!1).catch(!1),autoUpdateEnabled:j2.boolean().default(!0).catch(!0),disabledTools:FY.optional(),disabledPlugins:FY.optional()}).strip().transform(($)=>{let f={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});var QB={};w(QB,{updateMcpServerOAuthState:()=>Bf,setMcpServerDisabled:()=>Yf,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>M0,registerMcpServersFromSettingsFile:()=>Hf,normalizeMcpServerOAuthState:()=>q2,loadMcpSettingsFile:()=>Xf,listMcpServerOAuthStatuses:()=>I4,hasMcpSettingsFile:()=>v1,getMcpServerOAuthState:()=>Vf});import{existsSync as W_,mkdirSync as tV,readFileSync as dZ,writeFileSync as oV}from"node:fs";import{dirname as eV}from"node:path";import{resolveMcpSettingsPath as j_}from"@cline/shared/storage";import{z as C}from"zod";function uZ($){if(!$)return;if($==="http")return"streamableHttp";return $}function M0(){return j_()}function D_($){let f=dZ($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function JB($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function R_($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function Xf($={}){let f=$.filePath??M0(),J=dZ(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=P_.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${W}`)}return Z.data}function U_($){let f=dZ($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Q}function q2($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function z_($){if($===void 0)return;let f=lZ.safeParse($);if(!f.success)return;return q2(f.data)}function v1($={}){let f=$.filePath??M0();return W_(f)}function A1($={}){let f=Xf($);return Object.entries(f.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function Yf($){let f=$.filePath??M0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=D_(f),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let W={...Z},j=JB(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;R_(W,J,X),tV(eV(f),{recursive:!0}),oV(f,`${JSON.stringify({...Q,mcpServers:W},null,2)}
|
|
4
|
+
`)}function Vf($,f={}){let J=Xf(f);if(!Object.hasOwn(J.mcpServers,$))return;return q2(J.mcpServers[$]?.oauth)}function Bf($,f,J={}){let Q=J.filePath??M0(),Z=U_(Q),W=Z.mcpServers,j=JB(W,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let X=z_(j.oauth)??{},Y=q2(f(X));if(Y)j.oauth=Y;else delete j.oauth;return tV(eV(Q),{recursive:!0}),oV(Q,`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),Y??{}}function I4($={}){return A1($).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function Hf($,f={}){let J=A1(f);for(let Q of J)await $.registerServer(Q);return J}var k4,$B,lZ,X_,Y_,V_,B_,H_,A_,fB,K_,G_,F_,P_;var O5=h$(()=>{k4=C.record(C.string(),C.string()),$B=C.record(C.string(),C.unknown()),lZ=C.object({clientInformation:C.record(C.string(),C.unknown()).optional(),tokens:C.record(C.string(),C.unknown()).optional(),codeVerifier:C.string().optional(),discoveryState:C.record(C.string(),C.unknown()).optional(),redirectUrl:C.string().url().optional(),lastError:C.string().optional(),lastAuthenticatedAt:C.number().int().positive().optional()}).strip(),X_=C.object({type:C.literal("stdio"),command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:k4.optional()}),Y_=C.object({type:C.literal("sse"),url:C.string().url(),headers:k4.optional()}),V_=C.object({type:C.literal("streamableHttp"),url:C.string().url(),headers:k4.optional()}),B_=C.discriminatedUnion("type",[X_,Y_,V_]),H_=C.object({transport:B_,disabled:C.boolean().optional(),metadata:$B.optional(),oauth:lZ.optional()}),A_=C.enum(["stdio","sse","http","streamableHttp"]).optional(),fB=C.object({type:C.enum(["stdio","sse","streamableHttp"]).optional(),transportType:A_,disabled:C.boolean().optional(),metadata:$B.optional(),oauth:lZ.optional()});K_=fB.extend({command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:k4.optional()}).superRefine(($,f)=>{let J=$.type??uZ($.transportType);if(J&&J!=="stdio")f.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),G_=fB.extend({url:C.string().url(),headers:k4.optional()}).superRefine(($,f)=>{let J=$.type??uZ($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??uZ($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth}}),F_=C.union([H_,K_,G_]),P_=C.object({mcpServers:C.record(C.string(),F_)}).passthrough()});import{existsSync as zN,mkdirSync as LN,readFileSync as _N,writeFileSync as ON}from"node:fs";import{resolve as MN}from"node:path";import{resolveSessionDataDir as TN}from"@cline/shared/storage";import{nanoid as NN}from"nanoid";import*as qN from"node-machine-id";function h0($){let f=$?.trim();if(f)return f;let J=SN();if(J)return J;return CN()}function yN(){let $=qN;return $.machineIdSync??$.default?.machineIdSync}function SN(){try{let $=yN();if(!$)return;return $().trim()||void 0}catch{return}}function CN(){let $=TN(),f=MN($,wN);try{if(zN(f)){let Q=_N(f,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${NN()}`;try{LN($,{recursive:!0}),ON(f,J,"utf8")}catch{}return J}var wN="machine-id";var I2=()=>{};class A6{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get($);if(!W)W=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,W);W.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get($);if(!W)W=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,W);W.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Q?{description:Q}:void 0);V.addCallback((B)=>{for(let H of this.snapshotGaugeSeries($))B.observe(H.value,this.flattenProperties(H.attributes))}),this.gauges.set($,V)}Y.set(j,{value:f,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,Q=0){if(!$)return{};let Z={},W=100,j=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=f?`${f}.${X}`:X;if(Y===null||Y===void 0){Z[V]=String(Y);continue}if(Array.isArray(Y)){let B=Y.length>W?Y.slice(0,W):Y;try{Z[V]=JSON.stringify(B)}catch{Z[V]="[UnserializableArray]"}if(Y.length>W)Z[`${V}_truncated`]=!0,Z[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){Z[V]=Y.toISOString();continue}if(Y instanceof Error){Z[V]=Y.message;continue}if(J.has(Y)){Z[V]="[Circular]";continue}if(Q>=j){Z[V]="[MaxDepthExceeded]";continue}J.add(Y),Object.assign(Z,this.flattenProperties(Y,V,J,Q+1));continue}if(iq(Y)){Z[V]=Y;continue}try{Z[V]=JSON.stringify(Y)}catch{Z[V]=String(Y)}}return Z}}function iq($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class K6{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordHistogram($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordGauge($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class a2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new K6({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let Q of this.adapters)Q.emitRequired($,J)}recordCounter($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,W,Q,Z)}recordHistogram($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,W,Q,Z)}recordGauge($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,W,Q,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var $W=()=>{};import{metrics as nq,trace as aq}from"@opentelemetry/api";import{logs as sq}from"@opentelemetry/api-logs";import{OTLPLogExporter as tq}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as oq}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as eq}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as $w}from"@opentelemetry/resources";import{BatchLogRecordProcessor as fw,ConsoleLogRecordExporter as Jw,LoggerProvider as Qw}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as Zw,MeterProvider as Ww,PeriodicExportingMetricReader as LA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as jw,ConsoleSpanExporter as Xw,SimpleSpanProcessor as Yw}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Vw}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as Bw,ATTR_SERVICE_VERSION as Hw}from"@opentelemetry/semantic-conventions";class _A{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class s2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=$w({[Bw]:$.serviceName??"cline",...$.serviceVersion?{[Hw]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)nq.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)sq.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return aq.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new A6({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new a2({...$,adapters:[f],distinctId:h0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=fW(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=f.map((W)=>Gw(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new Ww({resource:$,readers:Z})}createTracerProvider($){let f=fW(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of f){let j=Kw(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new Vw({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=fW(this.options.logsExporter);if(f.length===0)return null;let J=f.map((Q)=>{let Z=Aw(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new fw(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new Qw({resource:$,processors:J})}}function G6($){let f=new s2($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function a1($){if(TJ())return{telemetry:new _A($)};if($.enabled!==!0)return{telemetry:new a2({...$,distinctId:h0($.distinctId)})};return G6($)}function t2($){let{telemetry:f,provider:J}=a1($);return{telemetry:f,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function fW($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function Aw($,f){if($==="console")return new Jw;if(!f.endpoint)return null;let J=JW(f.endpoint,"/v1/logs");return new tq({url:J,headers:f.headers})}function Kw($,f){if($==="console")return new Yw(new Xw);if(!f.endpoint)return null;let J=JW(f.endpoint,"/v1/traces");return new jw(new eq({url:J,headers:f.headers}))}function Gw($,f){if($==="console")return new LA({exporter:new Zw,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=JW(f.endpoint,"/v1/metrics");return new LA({exporter:new oq({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function JW($,f){let J=new URL($),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith(f)?Q:`${Q}${f}`,J.toString()}var W9=h$(()=>{H1();I2();$W()});var yK={};w(yK,{resolveCoreDistinctId:()=>h0,createOpenTelemetryTelemetryService:()=>G6,createConfiguredTelemetryService:()=>a1,createConfiguredTelemetryHandle:()=>t2,OpenTelemetryProvider:()=>s2,OpenTelemetryAdapter:()=>A6});var F9=h$(()=>{I2();W9()});import{AgentRuntimeAbortError as tE}from"@cline/agents";import{initVcr as oE,resolveClineBuildEnv as eE}from"@cline/shared";import{normalizeProviderId as nE}from"@cline/llms";var wG={};w(wG,{LocalRuntimeHost:()=>z1});import{readdirSync as mE}from"node:fs";import{homedir as vE}from"node:os";import{isAbsolute as cE,join as M3,resolve as T3}from"node:path";import{captureSdkError as hf,createSessionId as uE,isLikelyAuthError as dE,normalizeUserInput as lE}from"@cline/shared";import{setHomeDirIfUnset as pE}from"@cline/shared/storage";var Hj={};w(Hj,{saveProviderOAuthCredentials:()=>I$,resolveProviderApiKeyFromSettings:()=>ZQ,loginAndSaveProviderOAuthCredentials:()=>D8,isOAuthProvider:()=>k$,getProviderOAuthCredentialsFromSettings:()=>R8,getProviderAuthStorageId:()=>QQ,getProviderAuthHandler:()=>Q0,getPersistedProviderApiKey:()=>df,formatProviderOAuthApiKey:()=>WQ});import{getClineEnvironmentConfig as Vj}from"@cline/shared";L0();var r3={};w(r3,{startClineDeviceAuth:()=>o9,refreshClineToken:()=>a6,loginClineOAuth:()=>B8,getValidClineCredentials:()=>H8,completeClineDeviceAuth:()=>e9});import{getClineEnvironmentConfig as i9}from"@cline/shared";var x3={};w(x3,{startLocalOAuthServer:()=>f1});function nG(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function f1($){let f=await import("node:http"),J=$.host??"127.0.0.1",Q=$.timeoutMs??300000,Z=$.successHtml??aG,W=nG(),j=!1,X=null,Y=null,V=null,B=(K)=>{if(j)return;j=!0,W.resolve(K)},H=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{H(),B(null)},Q),W.promise};for(let K of $.ports){let G=f.createServer((P,F)=>{try{let D=new URL(P.url||"",`http://${J}:${K}`);if(D.pathname!==$.callbackPath){F.statusCode=404,F.end("Not found");return}let _={url:D,code:D.searchParams.get("code")??void 0,state:D.searchParams.get("state")??void 0,provider:D.searchParams.get("provider")??void 0,error:D.searchParams.get("error")??void 0};if(_.error){F.statusCode=400,F.end(`Authentication failed: ${_.error}`),H(),B(_);return}if(!_.code){F.statusCode=400,F.end("Missing authorization code");return}if($.expectedState&&_.state!==$.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(Z),H(),B(_)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((P)=>{let F=(D)=>{G.off("error",F),P({bound:!1,error:D})};G.once("error",F),G.listen(K,J,()=>{G.off("error",F),Y=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw H(),R.error}if(R.bound){V=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:A,cancelWait:()=>{H(),B(null)},close:()=>{H(),B(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var aG=`<!DOCTYPE html>
|
|
6
6
|
<html lang="en">
|
|
7
7
|
<head>
|
|
8
8
|
<meta charset="utf-8">
|
|
@@ -43,22 +43,22 @@ import{createRequire as fP}from"node:module";var{defineProperty:S9,getOwnPropert
|
|
|
43
43
|
</div>
|
|
44
44
|
<script>setTimeout(() => window.close(), 3000);</script>
|
|
45
45
|
</body>
|
|
46
|
-
</html>`;function F3(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 XP(f){let J=new TextEncoder().encode(f),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function AP(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),F3($)}async function m4(){let f=AP(),$=F3(await XP(f));return{verifier:f,challenge:$}}function g4(f){return f.endsWith("/")?f.slice(0,-1):f}function b$(f,$){return new URL($,`${g4(f)}/`).toString()}function k1(f,$={}){let J=f.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:$.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:$.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function YP(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 O0(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=YP(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function I1(f){try{let $=JSON.parse(f),J=$.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function x1(f,$){return Date.now()>=f.expires-$}async function m1(f){if(!f.onManualCodeInput){let W=await f.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let $,J,Q=f.onManualCodeInput().then((W)=>{$=W,f.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),f.cancelWait()}),Z=await f.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if($)return k1($,f.parseOptions);if(await Q,J)throw J;if($)return k1($,f.parseOptions);return{}}var v4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},L3={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},h9="https://api.workos.com",VP="/auth",U3=Array.from({length:11},(f,$)=>48801+$),BP=300000,KP=30000,g1=30000,PP=300,GP=5;class ef 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 FP(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function b9(f,$,J={}){let Q=f.userInfo.clineUserId??J.accountId,Z=f.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:Z,expires:FP(f.expiresAt),accountId:Q??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function k9(f){if(!f)return{};return typeof f==="function"?await f():f}function R3(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function D3(f){await new Promise(($)=>setTimeout($,f))}function I9(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function _3(f,$){let J=await fetch(b$(h9,L3.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??g1)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new ef(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:R3(Q.expires_in,PP),pollIntervalSeconds:R3(Q.interval,GP)}}async function O3(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let Q=await fetch(b$(f.workosApiBaseUrl,L3.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)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await D3(J*1000);break}case"slow_down":{J+=1,await D3(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new ef(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new ef(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function T3(f,$,J){let Q={accessToken:f.accessToken,refreshToken:f.refreshToken},Z=await fetch(b$($.apiBaseUrl,v4.register),{method:"POST",headers:{"Content-Type":"application/json",...await k9($.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout($.requestTimeoutMs??g1)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=I1(j);throw new ef(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let W=await Z.json();return b9(I9(W,"Invalid token exchange response"),J??$.provider)}async function UP(f,$,J,Q){let Z={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:Q??J.provider},W=await fetch(b$(J.apiBaseUrl,v4.token),{method:"POST",headers:{"Content-Type":"application/json",...await k9(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??g1)});if(!W.ok){let H=await W.text().catch(()=>""),X=I1(H);throw new ef(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return b9(I9(j,"Invalid token exchange response"),Q??J.provider)}async function $8(f){Mf(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:U3,Q=f.callbackPath??VP,Z=$?null:await e0({ports:J,callbackPath:Q,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??U3[0]}${Q}`;try{let j;if($){let H=E9().workOsClientId,X=await _3(H,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await O3({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??g1,workosApiBaseUrl:h9,onProgress:f.callbacks.onProgress});j=await T3(A,f,f.provider)}else{let H=new URL(b$(f.apiBaseUrl,v4.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",W),H.searchParams.set("redirect_uri",W),f.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,A=f.provider,Y=await m1({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(Y.error)throw Error(`OAuth error: ${Y.error}`);if(X=Y.code,A=Y.provider??A,!X){let V=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=k1(V,{includeProvider:!0});X=B.code,A=B.provider??A}if(!X)throw Error("Missing authorization code");j=await UP(X,W,f,A)}return Nf(f.telemetry,f.provider??"cline"),yf(f.telemetry,{id:j.accountId,email:j.email,provider:f.provider??"cline"}),j}catch(j){throw qf(f.telemetry,f.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function x9(f){return await _3(E9().workOsClientId,f)}async function m9(f){let $=f.provider??"cline";Mf(f.telemetry,$);try{let J=await O3({clientId:E9().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??g1,workosApiBaseUrl:h9}),Q=await T3(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return Nf(f.telemetry,$),yf(f.telemetry,{id:Q.accountId,email:Q.email,provider:$}),Q}catch(J){throw qf(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function c4(f,$){let J=await fetch(b$($.apiBaseUrl,v4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await k9($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??g1)});if(!J.ok){let W=await J.text().catch(()=>""),j=I1(W);throw new ef(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=f.metadata?.provider??$.provider;return b9(I9(Q,"Invalid token refresh response"),Z,f)}async function J8(f,$,J){if(!f)return null;let Q=J?.refreshBufferMs??BP,Z=J?.retryableTokenGraceMs??KP;if(J?.forceRefresh!==!0&&!x1(f,Q))return f;try{return await c4(f,$)}catch(j){if(j instanceof ef&&j.isLikelyInvalidGrant())return sf($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}_0();var N3={};q(N3,{refreshOpenAICodexToken:()=>d4,loginOpenAICodex:()=>Q8,getValidOpenAICodexCredentials:()=>Z8,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as RP}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class u4 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 DP(f,$,J=e.redirectUri){let Q=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function LP(f){try{let $=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!$.ok){let Q=await $.text().catch(()=>""),Z=I1(Q);throw new u4(`Token refresh failed: ${$.status}${Z.message?` - ${Z.message}`:""}`,{status:$.status,errorCode:Z.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 u4)throw $;return{type:"failed"}}}async function _P(f="pi"){let{verifier:$,challenge:J}=await m4(),Q=RP(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",f),{verifier:$,state:Q,url:Z.toString()}}function OP(){try{let f=new URL(e.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):e.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:e.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function TP(f,$){let J=$?O0($):O0(f),Q=J?J:O0(f),W=Q?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=Q?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function M3(f,$){let J=TP(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 Q8(f){Mf(f.telemetry,"openai-codex");let $=OP(),{verifier:J,state:Q,url:Z}=await _P(f.originator),W=await e0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:Q});f.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await m1({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==Q)throw Error("State mismatch");if(j=H.code,!j){let Y=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=k1(Y,{allowHashCodeState:!0});if(V.state&&V.state!==Q)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await DP(j,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=M3(X);return Nf(f.telemetry,"openai-codex"),yf(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(H){throw qf(f.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{W.close()}}async function d4(f,$){let J=await LP(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=M3(J,$);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function Z8(f,$){if(!f)return null;let J=$?.refreshBufferMs??e.refreshBufferMs,Q=$?.retryableTokenGraceMs??e.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!x1(f,J))return f;try{return await d4(f.refresh,f)}catch(W){if(W instanceof u4&&W.isLikelyInvalidGrant())return sf($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>Q)return f;return null}}_0();var v3={};q(v3,{refreshOcaToken:()=>i4,loginOcaOAuth:()=>j8,getValidOcaCredentials:()=>H8,OCI_HEADER_OPC_REQUEST_ID:()=>zP,DEFAULT_INTERNAL_OCA_BASE_URL:()=>l4,DEFAULT_INTERNAL_IDCS_URL:()=>w3,DEFAULT_INTERNAL_IDCS_SCOPES:()=>C3,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>y3,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>p4,DEFAULT_EXTERNAL_IDCS_URL:()=>E3,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>h3,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>S3});import{nanoid as q3}from"nanoid";class g9{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(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set(f,{value:$,expiresAt:J+Q})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var y3="a8331954c0cf48ba99b5dd223a14c6ea",w3="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",C3="openid offline_access",l4="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",S3="c1aba3deed5740659981a752714eba33",E3="https://login-ext.identity.oraclecloud.com",h3="openid offline_access",p4="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",zP="opc-request-id",MP="/auth/oca",NP=Array.from({length:11},(f,$)=>48801+$),qP=300000,yP=30000,b3=30000,wP=600000;class r4 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 f$={internal:{clientId:y3,idcsUrl:w3,scopes:C3,baseUrl:l4},external:{clientId:S3,idcsUrl:E3,scopes:h3,baseUrl:p4}},W8=new Map,CP=86400000,SP=300000,EP=32,v9=new g9(CP,EP);function k3(f){if(typeof f==="function")return f();return f??"internal"}function I3(f){return{internal:{clientId:f?.internal?.clientId??f$.internal.clientId,idcsUrl:f?.internal?.idcsUrl??f$.internal.idcsUrl,scopes:f?.internal?.scopes??f$.internal.scopes,baseUrl:f?.internal?.baseUrl??f$.internal.baseUrl},external:{clientId:f?.external?.clientId??f$.external.clientId,idcsUrl:f?.external?.idcsUrl??f$.external.idcsUrl,scopes:f?.external?.scopes??f$.external.scopes,baseUrl:f?.external?.baseUrl??f$.external.baseUrl}}}function hP(f=Date.now()){let $=f-wP;for(let[J,Q]of W8.entries())if(Q.createdAt<$)W8.delete(J)}function bP(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let Z=O0($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=O0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function x3(f,$,J){let Q=f.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=f.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=O0(f.id_token),j=O0(Q),H=W?.sub??j?.sub,X=W?.email??j?.email;return{access:Q,refresh:Z,expires:bP(f,Q,f.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:H,idToken:f.id_token}}}async function m3(f,$){let J=g4(f),Q=v9.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout($)});if(!W.ok){let X=`${J}/oauth2/v1/token`;return v9.set(J,X,Date.now(),SP),X}let H=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return v9.set(J,H),H}function g3(f){return{code:f.error,message:f.error_description}}async function kP(f){let $=W8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");W8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,Q=await m3(J.idcsUrl,f.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout(f.requestTimeoutMs)}),j=await W.json();if(!W.ok){let X=g3(j);throw new r4(`Token exchange failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let H=O0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return x3(j,f.mode)}function IP(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${g4($.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 j8(f){Mf(f.telemetry,"oca");let $=I3(f.config),J=k3(f.mode),Q=f.callbackPorts?.length?f.callbackPorts:NP,Z=f.callbackPath??MP,W=f.requestTimeoutMs??b3,j=await e0({ports:Q,callbackPath:Z,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=q3(16),A=q3(16),{verifier:Y,challenge:V}=await m4();hP(),W8.set(X,{verifier:Y,nonce:A,mode:J,redirectUri:H,createdAt:Date.now()});let B=IP({callbackUrl:H,mode:J,state:X,nonce:A,challenge:V,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await m1({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),P=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!P){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==X)throw Error("State mismatch");let G=await kP({code:P,state:R,mode:J,config:$,requestTimeoutMs:W});return Nf(f.telemetry,"oca"),yf(f.telemetry,{id:G.accountId,email:G.email,provider:"oca"}),G}catch(K){throw qf(f.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function i4(f,$={}){let J=I3($.config),Q=$.requestTimeoutMs??b3,Z=f.metadata?.mode,W=Z==="internal"||Z==="external"?Z:k3($.mode),j=W==="external"?J.external:J.internal,H=await m3(j.idcsUrl,Q),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:j.clientId}),A=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(Q)}),Y=await A.json();if(!A.ok){let V=g3(Y);throw new r4(`Token refresh failed: ${A.status}${V.message?` - ${V.message}`:""}`,{status:A.status,errorCode:V.code})}return x3(Y,W,f)}async function H8(f,$,J){if(!f)return null;let Q=$?.refreshBufferMs??J?.refreshBufferMs??qP,Z=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??yP;if($?.forceRefresh!==!0&&!x1(f,Q))return f;try{return await i4(f,J)}catch(j){if(j instanceof r4&&j.isLikelyInvalidGrant())return sf(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>Z)return f;return null}}var n4="workos:";function xP(f){let $=f.trim();return $.toLowerCase().startsWith(n4)?$:`${n4}${$}`}function mP(f){let $=f.trim();return $.toLowerCase().startsWith(n4)?$.slice(n4.length):$}function gP(f){let J=O0(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function vP(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=gP($);if(Q)return Q;return Date.now()-1}function cP(f,$){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=$?.normalizeAccessToken?.(J)??J;if(!Z)return null;return{access:Z,refresh:Q,expires:vP(f,Z),accountId:f.auth?.accountId}}function uP(f){let $=f.formatAccessToken?.(f.credentials.access)??f.credentials.access,J={...f.settings?.auth??{},accessToken:$,refreshToken:f.credentials.refresh,accountId:f.credentials.accountId,expiresAt:f.credentials.expires},Q={...f.settings??{provider:f.storageProviderId},provider:f.storageProviderId,auth:J};if(f.save!==!1)f.manager.saveProviderSettings(Q,{...f.setLastUsed===void 0?{}:{setLastUsed:f.setLastUsed},tokenSource:"oauth"});return Q}function c9(f){let $=f.storageProviderId??f.providerId;return{providerId:f.providerId,storageProviderId:$,getApiKey(J){let Q=J?.auth?.accessToken?.trim();if(Q)return f.formatAccessToken?.(Q)??Q;return J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0},login:f.login,refresh:f.refresh,saveCredentials(J){return uP({...J,storageProviderId:$,formatAccessToken:f.formatAccessToken})},isConfigured(J){return!!J?.auth?.accessToken},normalizeStoredAccessToken:f.normalizeStoredAccessToken}}var dP=[c9({providerId:"cline",formatAccessToken:xP,normalizeStoredAccessToken:mP,login:({settings:f,callbacks:$,telemetry:J})=>$8({apiBaseUrl:f?.baseUrl?.trim()||c3().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>J8($,{apiBaseUrl:f.baseUrl?.trim()||c3().apiBaseUrl,telemetry:Q},{forceRefresh:J})}),c9({providerId:"oca",login:({settings:f,callbacks:$,telemetry:J})=>j8({mode:f?.oca?.mode,callbacks:$,telemetry:J}),refresh:({settings:f,credentials:$,forceRefresh:J,telemetry:Q})=>H8($,{forceRefresh:J,telemetry:Q},{mode:f.oca?.mode,telemetry:Q})}),c9({providerId:"openai-codex",login:({callbacks:f,telemetry:$})=>Q8({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput,telemetry:$}),refresh:({credentials:f,forceRefresh:$,telemetry:J})=>Z8(f,{forceRefresh:$,telemetry:J})})],lP=new Map(dP.map((f)=>[f.providerId,f]));function V0(f){return lP.get(f.trim().toLowerCase())}function k$(f){return V0(f)!==void 0}function u9(f){return V0(f)?.storageProviderId}function d9(f,$){let J=V0($),Q=J?.storageProviderId??$,Z=f.getProviderSettings(Q);return J?.getApiKey(Z)??a4($,Z)}async function X8(f,$,J){let Q=V0($);if(!Q)throw Error(`Provider "${$}" does not support OAuth login`);let Z=f.getProviderSettings(Q.storageProviderId),W=await Q.login({settings:Z,callbacks:J.callbacks,telemetry:J.telemetry});return Q.saveCredentials({manager:f,settings:Z,credentials:W})}function A8(f,$){let J=V0(f);if(!J)return null;return cP($,{normalizeAccessToken:J.normalizeStoredAccessToken})}function I$(f){let $=V0(f.providerId);if(!$)throw Error(`Provider "${f.providerId}" does not support OAuth credentials`);return $.saveCredentials({manager:f.manager,settings:f.settings,credentials:f.credentials,setLastUsed:f.setLastUsed,save:f.save})}function a4(f,$){let J=V0(f);if(J)return J.getApiKey($);return $?.auth?.accessToken?.trim()||$?.apiKey?.trim()||$?.auth?.apiKey?.trim()||void 0}function l9(f,$){let J=V0(f);if(!J)return $.access;return J.getApiKey({provider:J.storageProviderId,auth:{accessToken:$.access}})??$.access}_0();var Pj={};q(Pj,{createContextCompactionPrepareTurn:()=>G8});import{createHandlerAsync as aP}from"@cline/llms";import{estimateTokens as p9}from"@cline/shared";var p3=200000,r9=0.9,r3=16384,i9=20000,d3=1024,l3=2000,i3=2000,n3=8;function $$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
|
|
47
|
-
...[truncated ${f
|
|
46
|
+
</html>`;function g3($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function sG($){let J=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function tG($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),g3(f)}async function r6(){let $=tG(),f=g3(await sG($));return{verifier:$,challenge:f}}function i6($){return $.endsWith("/")?$.slice(0,-1):$}function b$($,f){return new URL(f,`${i6($)}/`).toString()}function gf($,f={}){let J=$.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:f.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:f.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function oG($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function _0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=oG(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function mf($){try{let f=JSON.parse($),J=f.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function vf($,f){return Date.now()>=$.expires-f}async function cf($){if(!$.onManualCodeInput){let W=await $.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let f,J,Q=$.onManualCodeInput().then((W)=>{f=W,$.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return gf(f,$.parseOptions);if(await Q,J)throw J;if(f)return gf(f,$.parseOptions);return{}}var n6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},u3={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},n9="https://api.workos.com",eG="/auth",m3=Array.from({length:11},($,f)=>48801+f),$F=300000,fF=30000,uf=30000,JF=300,QF=5;class $$ extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function ZF($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function a9($,f,J={}){let Q=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:ZF($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function s9($){if(!$)return{};return typeof $==="function"?await $():$}function v3($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function c3($){await new Promise((f)=>setTimeout(f,$))}function t9($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function d3($,f){let J=await fetch(b$(n9,u3.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??uf)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new $$(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:v3(Q.expires_in,JF),pollIntervalSeconds:v3(Q.interval,QF)}}async function l3($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let Q=await fetch(b$($.workosApiBaseUrl,u3.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await c3(J*1000);break}case"slow_down":{J+=1,await c3(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new $$(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new $$(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function p3($,f,J){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(b$(f.apiBaseUrl,n6.register),{method:"POST",headers:{"Content-Type":"application/json",...await s9(f.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(f.requestTimeoutMs??uf)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=mf(j);throw new $$(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let W=await Z.json();return a9(t9(W,"Invalid token exchange response"),J??f.provider)}async function WF($,f,J,Q){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:Q??J.provider},W=await fetch(b$(J.apiBaseUrl,n6.token),{method:"POST",headers:{"Content-Type":"application/json",...await s9(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??uf)});if(!W.ok){let X=await W.text().catch(()=>""),Y=mf(X);throw new $$(`Token exchange failed: ${W.status}${Y.message?` - ${Y.message}`:""}`,{status:W.status,errorCode:Y.code})}let j=await W.json();return a9(t9(j,"Invalid token exchange response"),Q??J.provider)}async function B8($){N1($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:m3,Q=$.callbackPath??eG,Z=f?null:await f1({ports:J,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??m3[0]}${Q}`;try{let j;if(f){let X=i9().workOsClientId,Y=await d3(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await l3({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??uf,workosApiBaseUrl:n9,onProgress:$.callbacks.onProgress});j=await p3(V,$,$.provider)}else{let X=new URL(b$($.apiBaseUrl,n6.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",W),X.searchParams.set("redirect_uri",W),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,B=await cf({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(B.error)throw Error(`OAuth error: ${B.error}`);if(Y=B.code,V=B.provider??V,!Y){let H=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=gf(H,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");j=await WF(Y,W,$,V)}return q1($.telemetry,$.provider??"cline"),y1($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw w1($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function o9($){return await d3(i9().workOsClientId,$)}async function e9($){let f=$.provider??"cline";N1($.telemetry,f);try{let J=await l3({clientId:i9().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??uf,workosApiBaseUrl:n9}),Q=await p3(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return q1($.telemetry,f),y1($.telemetry,{id:Q.accountId,email:Q.email,provider:f}),Q}catch(J){throw w1($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function a6($,f){let J=await fetch(b$(f.apiBaseUrl,n6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await s9(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??uf)});if(!J.ok){let W=await J.text().catch(()=>""),j=mf(W);throw new $$(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=$.metadata?.provider??f.provider;return a9(t9(Q,"Invalid token refresh response"),Z,$)}async function H8($,f,J){if(!$)return null;let Q=J?.refreshBufferMs??$F,Z=J?.retryableTokenGraceMs??fF;if(J?.forceRefresh!==!0&&!vf($,Q))return $;try{return await a6($,f)}catch(j){if(j instanceof $$&&j.isLikelyInvalidGrant())return o1(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}L0();var n3={};w(n3,{refreshOpenAICodexToken:()=>t6,loginOpenAICodex:()=>A8,getValidOpenAICodexCredentials:()=>K8,OPENAI_CODEX_OAUTH_CONFIG:()=>$0});import{nanoid as jF}from"nanoid";var $0={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 s6 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function XF($,f,J=$0.redirectUri){let Q=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$0.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function YF($){try{let f=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:$0.clientId}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!f.ok){let Q=await f.text().catch(()=>""),Z=mf(Q);throw new s6(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof s6)throw f;return{type:"failed"}}}async function VF($="pi"){let{verifier:f,challenge:J}=await r6(),Q=jF(32),Z=new URL($0.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",$0.clientId),Z.searchParams.set("redirect_uri",$0.redirectUri),Z.searchParams.set("scope",$0.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:Q,url:Z.toString()}}function BF(){try{let $=new URL($0.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):$0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:$0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:$0.callbackPort,callbackPath:"/auth/callback",redirectUri:$0.redirectUri}}}function HF($,f){let J=f?_0(f):_0($),Q=J?J:_0($),W=Q?.[$0.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let Y=j[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function i3($,f){let J=HF($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function A8($){N1($.telemetry,"openai-codex");let f=BF(),{verifier:J,state:Q,url:Z}=await VF($.originator),W=await f1({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:Q});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await cf({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Q)throw Error("State mismatch");if(j=X.code,!j){let B=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),H=gf(B,{allowHashCodeState:!0});if(H.state&&H.state!==Q)throw Error("State mismatch");j=H.code}if(!j)throw Error("Missing authorization code");let Y=await XF(j,J,f.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=i3(Y);return q1($.telemetry,"openai-codex"),y1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw w1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{W.close()}}async function t6($,f){let J=await YF($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=i3(J,f);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function K8($,f){if(!$)return null;let J=f?.refreshBufferMs??$0.refreshBufferMs,Q=f?.retryableTokenGraceMs??$0.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!vf($,J))return $;try{return await t6($.refresh,$)}catch(W){if(W instanceof s6&&W.isLikelyInvalidGrant())return o1(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}L0();var Yj={};w(Yj,{refreshOcaToken:()=>fJ,loginOcaOAuth:()=>F8,getValidOcaCredentials:()=>P8,OCI_HEADER_OPC_REQUEST_ID:()=>AF,DEFAULT_INTERNAL_OCA_BASE_URL:()=>o6,DEFAULT_INTERNAL_IDCS_URL:()=>t3,DEFAULT_INTERNAL_IDCS_SCOPES:()=>o3,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>s3,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>e6,DEFAULT_EXTERNAL_IDCS_URL:()=>$j,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>fj,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>e3});import{nanoid as a3}from"nanoid";class $Q{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+Q})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var s3="a8331954c0cf48ba99b5dd223a14c6ea",t3="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",o3="openid offline_access",o6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",e3="c1aba3deed5740659981a752714eba33",$j="https://login-ext.identity.oraclecloud.com",fj="openid offline_access",e6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",AF="opc-request-id",KF="/auth/oca",GF=Array.from({length:11},($,f)=>48801+f),FF=300000,PF=30000,Jj=30000,DF=600000;class $J extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var f$={internal:{clientId:s3,idcsUrl:t3,scopes:o3,baseUrl:o6},external:{clientId:e3,idcsUrl:$j,scopes:fj,baseUrl:e6}},G8=new Map,RF=86400000,UF=300000,zF=32,fQ=new $Q(RF,zF);function Qj($){if(typeof $==="function")return $();return $??"internal"}function Zj($){return{internal:{clientId:$?.internal?.clientId??f$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??f$.internal.idcsUrl,scopes:$?.internal?.scopes??f$.internal.scopes,baseUrl:$?.internal?.baseUrl??f$.internal.baseUrl},external:{clientId:$?.external?.clientId??f$.external.clientId,idcsUrl:$?.external?.idcsUrl??f$.external.idcsUrl,scopes:$?.external?.scopes??f$.external.scopes,baseUrl:$?.external?.baseUrl??f$.external.baseUrl}}}function LF($=Date.now()){let f=$-DF;for(let[J,Q]of G8.entries())if(Q.createdAt<f)G8.delete(J)}function _F($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=_0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=_0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function Wj($,f,J){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=_0($.id_token),j=_0(Q),X=W?.sub??j?.sub,Y=W?.email??j?.email;return{access:Q,refresh:Z,expires:_F($,Q,$.id_token),accountId:X??J?.accountId,email:Y??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function jj($,f){let J=i6($),Q=fQ.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!W.ok){let Y=`${J}/oauth2/v1/token`;return fQ.set(J,Y,Date.now(),UF),Y}let X=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return fQ.set(J,X),X}function Xj($){return{code:$.error,message:$.error_description}}async function OF($){let f=G8.get($.state);if(!f)throw Error("No PKCE verifier found for this state");G8.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,Q=await jj(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await W.json();if(!W.ok){let Y=Xj(j);throw new $J(`Token exchange failed: ${W.status}${Y.message?` - ${Y.message}`:""}`,{status:W.status,errorCode:Y.code})}let X=_0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return Wj(j,$.mode)}function MF($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${i6(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function F8($){N1($.telemetry,"oca");let f=Zj($.config),J=Qj($.mode),Q=$.callbackPorts?.length?$.callbackPorts:GF,Z=$.callbackPath??KF,W=$.requestTimeoutMs??Jj,j=await f1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=a3(16),V=a3(16),{verifier:B,challenge:H}=await r6();LF(),G8.set(Y,{verifier:B,nonce:V,mode:J,redirectUri:X,createdAt:Date.now()});let A=MF({callbackUrl:X,mode:J,state:Y,nonce:V,challenge:H,config:f});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await cf({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==Y)throw Error("State mismatch");let P=await OF({code:G,state:R,mode:J,config:f,requestTimeoutMs:W});return q1($.telemetry,"oca"),y1($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw w1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function fJ($,f={}){let J=Zj(f.config),Q=f.requestTimeoutMs??Jj,Z=$.metadata?.mode,W=Z==="internal"||Z==="external"?Z:Qj(f.mode),j=W==="external"?J.external:J.internal,X=await jj(j.idcsUrl,Q),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Q)}),B=await V.json();if(!V.ok){let H=Xj(B);throw new $J(`Token refresh failed: ${V.status}${H.message?` - ${H.message}`:""}`,{status:V.status,errorCode:H.code})}return Wj(B,W,$)}async function P8($,f,J){if(!$)return null;let Q=f?.refreshBufferMs??J?.refreshBufferMs??FF,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??PF;if(f?.forceRefresh!==!0&&!vf($,Q))return $;try{return await fJ($,J)}catch(j){if(j instanceof $J&&j.isLikelyInvalidGrant())return o1(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}var JJ="workos:";function TF($){let f=$.trim();return f.toLowerCase().startsWith(JJ)?f:`${JJ}${f}`}function NF($){let f=$.trim();return f.toLowerCase().startsWith(JJ)?f.slice(JJ.length):f}function qF($){let J=_0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function wF($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=qF(f);if(Q)return Q;return Date.now()-1}function yF($,f){let J=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=f?.normalizeAccessToken?.(J)??J;if(!Z)return null;return{access:Z,refresh:Q,expires:wF($,Z),accountId:$.auth?.accountId}}function SF($){let f=$.formatAccessToken?.($.credentials.access)??$.credentials.access,J={...$.settings?.auth??{},accessToken:f,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:J};if($.save!==!1)$.manager.saveProviderSettings(Q,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Q}function JQ($){let f=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:f,getApiKey(J){let Q=J?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(J){return SF({...J,storageProviderId:f,formatAccessToken:$.formatAccessToken})},isConfigured(J){return!!J?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function Bj($){return JQ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:TF,normalizeStoredAccessToken:NF,login:({settings:f,callbacks:J,telemetry:Q})=>B8({apiBaseUrl:f?.baseUrl?.trim()||Vj().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:J,telemetry:Q}),refresh:({settings:f,credentials:J,forceRefresh:Q,telemetry:Z})=>H8(J,{apiBaseUrl:f.baseUrl?.trim()||Vj().apiBaseUrl,telemetry:Z},{forceRefresh:Q})})}var CF=[Bj({providerId:"cline"}),Bj({providerId:"cline-pass",storageProviderId:"cline"}),JQ({providerId:"oca",login:({settings:$,callbacks:f,telemetry:J})=>F8({mode:$?.oca?.mode,callbacks:f,telemetry:J}),refresh:({settings:$,credentials:f,forceRefresh:J,telemetry:Q})=>P8(f,{forceRefresh:J,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),JQ({providerId:"openai-codex",login:({callbacks:$,telemetry:f})=>A8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:f}),refresh:({credentials:$,forceRefresh:f,telemetry:J})=>K8($,{forceRefresh:f,telemetry:J})})],EF=new Map(CF.map(($)=>[$.providerId,$]));function Q0($){return EF.get($.trim().toLowerCase())}function k$($){return Q0($)!==void 0}function QQ($){return Q0($)?.storageProviderId}function ZQ($,f){let J=Q0(f),Q=J?.storageProviderId??f,Z=$.getProviderSettings(Q);return J?.getApiKey(Z)??df(f,Z)}async function D8($,f,J){let Q=Q0(f);if(!Q)throw Error(`Provider "${f}" does not support OAuth login`);let Z=$.getProviderSettings(Q.storageProviderId),W=await Q.login({settings:Z,callbacks:J.callbacks,telemetry:J.telemetry});return Q.saveCredentials({manager:$,settings:Z,credentials:W})}function R8($,f){let J=Q0($);if(!J)return null;return yF(f,{normalizeAccessToken:J.normalizeStoredAccessToken})}function I$($){let f=Q0($.providerId);if(!f)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return f.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function df($,f){let J=Q0($);if(J)return J.getApiKey(f);return f?.auth?.accessToken?.trim()||f?.apiKey?.trim()||f?.auth?.apiKey?.trim()||void 0}function WQ($,f){let J=Q0($);if(!J)return f.access;return J.getApiKey({provider:J.storageProviderId,auth:{accessToken:f.access}})??f.access}L0();var xj={};w(xj,{createContextCompactionPrepareTurn:()=>M8});import{createHandlerAsync as xF}from"@cline/llms";import{estimateTokens as jQ}from"@cline/shared";var Gj=200000,XQ=0.9,Fj=16384,YQ=20000,Aj=1024,Kj=2000,Pj=2000,Dj=8;function J$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
|
|
47
|
+
...[truncated ${$.length-f} chars]`}function hF($){let f=VQ($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
|
|
48
48
|
${J.content}
|
|
49
49
|
</file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
|
|
50
|
-
`)}function
|
|
51
|
-
`)}function
|
|
50
|
+
`)}function VQ($){if(typeof $==="string")return J$($,Kj);return $.map((f)=>{switch(f.type){case"text":return{...f,text:J$(f.text,Kj)};case"file":return{...f,content:J$(f.content,Pj)};case"image":return f;default:return f}})}function bF($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function Rj($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${J$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${bF(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${hF(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${J$(J.content,Pj)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
|
|
51
|
+
`)}function Uj($){return $.map(Rj).join(`
|
|
52
52
|
|
|
53
|
-
`).trim()}function
|
|
54
|
-
`):"- none",J
|
|
53
|
+
`).trim()}function zj(){let $=new WeakMap;return(f)=>{let J=f,Q=$.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify(f)}catch{Z=Rj(f)}let W=jQ(Z.length);return $.set(J,W),W}}function L8($){return $.metadata?.kind==="compaction_summary"}function BQ($){if(!L8($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function kF($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function _8($){return $.role==="user"&&!kF($)&&!L8($)}function Lj($){for(let f=0;f<$.length;f+=1)if(_8($[f]))return f;return-1}function QJ($){for(let f=$.length-1;f>=0;f-=1)if(_8($[f]))return f;return 0}function _j($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function Oj($){for(let f=$.length-1;f>=0;f-=1)if(L8($[f]))return f;return-1}function Mj($,f,J){let Q=QJ($);if(Q<=0)return 0;let Z=0,W=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),W=X,Z>=f)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!_8($[j]))j-=1;return j}function z8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>z8(f));if($&&typeof $==="object"){let f=$,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...z8(f[Q]));if(Array.isArray(f.files)){for(let Q of f.files)if(Q&&typeof Q==="object")J.push(...z8(Q.path))}if(Array.isArray(f.file_paths))J.push(...z8(f.file_paths));return J}return[]}function U8($,f){let J=new Set($);for(let Q of f){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function Tj($){let f=[],J=[];for(let Q of $){let Z=BQ(Q);if(Z){f=U8(f,Z.details.readFiles),J=U8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){f=U8(f,[W.path]);continue}if(W.type!=="tool_use")continue;let j=z8(W.input);if(W.name==="read_files"){f=U8(f,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=U8(J,j)}}return{readFiles:f,modifiedFiles:J}}function IF($){let f=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
|
|
54
|
+
`):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
|
|
55
55
|
`):"- none";return`## Files
|
|
56
56
|
Read:
|
|
57
|
-
${
|
|
57
|
+
${f}
|
|
58
58
|
Modified:
|
|
59
|
-
${J}`}function
|
|
59
|
+
${J}`}function Nj($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
|
|
60
60
|
|
|
61
|
-
${
|
|
61
|
+
${IF(f)}`.trim()}function qj($){let f=[`Summarize this session for continuation. Be concise and factual.
|
|
62
62
|
|
|
63
63
|
## Goal
|
|
64
64
|
One sentence: what is being built or fixed.
|
|
@@ -75,16 +75,24 @@ Key technical choices or notable findings (omit if none).
|
|
|
75
75
|
Immediate next steps.
|
|
76
76
|
|
|
77
77
|
## Files
|
|
78
|
-
Read: ${
|
|
79
|
-
Edited: ${
|
|
80
|
-
${
|
|
81
|
-
${
|
|
78
|
+
Read: ${$.fileOps.readFiles.join(", ")||"none"}
|
|
79
|
+
Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.trim())f.push(`Previous summary:
|
|
80
|
+
${$.previousSummary.trim()}`);return f.push(`Conversation:
|
|
81
|
+
${$.conversationText||"(empty)"}`),f.join(`
|
|
82
82
|
|
|
83
|
-
`)}function
|
|
83
|
+
`)}function wj($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??Aj,thinking:!1}};if(!f)return J($.activeProviderConfig);let Q=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...Q??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.headers??Q?.headers,knownModels:f.knownModels??Q?.knownModels,maxOutputTokens:f.maxOutputTokens??Aj})}function yj($){return{role:"user",content:`Context summary:
|
|
84
84
|
|
|
85
|
-
${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function tP(f){let $=await aP(f.providerConfig),J="";for await(let Q of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}function sP(f){try{return JSON.stringify(f).length}catch{return String(f).length}}async function Hj(f){let $=f.context.messages;if($.length<2)return;let J=$j($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let Q=$.slice(0,J),Z=fj(Q),W=Z>=0?a9(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let H=Jj(Q),X=t3(j),A=Zj({previousSummary:W,conversationText:X,fileOps:H});f.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:$.length-J,previousSummaryChars:W?.length??0,conversationTextChars:X.length,summaryRequestChars:A.length,summaryRequestEstimatedTokens:p9(A.length),newMessagesJsonChars:sP(j),maxInputTokens:f.context.maxInputTokens,triggerTokens:f.context.triggerTokens});let Y=await tP({providerConfig:Wj({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:A,logger:f.logger});if(!Y.trim())return;let V=Qj(Y,H),B=$.reduce((R,G)=>R+f.estimateMessageTokens(G),0),K=[jj({summary:V,fileOps:H,tokensBefore:B}),...$.slice(J)],P=K.reduce((R,G)=>R+f.estimateMessageTokens(G),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:B,tokensAfter:P,maxInputTokens:f.context.maxInputTokens}),{messages:K}}function Yj(f){if(B8(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.type==="tool_result"?{...J,content:n9(J.content)}:J)}}function P8(f,$){return f.reduce((J,Q)=>J+$(Q),0)}function Xj(f,$){let J=Math.max(1,$),Q=Math.max(16,J*4);if(typeof f.content==="string"){let j=$$(f.content,Q).trim();return{...f,content:j||"..."}}let Z=Q,W=f.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=$$(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...f,content:W}}function oP(f,$){let J=o3(f),Q=t4(f),Z=e3(f),W=[];for(let j=0;j<f.length;j+=1){let H=Yj(f[j]);if(!H)continue;W.push({index:j,message:H,estimatedTokens:$(H),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function Aj(f,$,J,Q){let Z=f[$];Z.message=J,Z.estimatedTokens=Q(J)}function eP(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_use")$.add(J.id);return $}function fG(f){let $=new Set;if(!Array.isArray(f.content))return $;for(let J of f.content)if(J.type==="tool_result")$.add(J.tool_use_id);return $}function Vj(f){return new Set([...eP(f.message),...fG(f.message)])}function $G(f){let $=new Map;for(let J=0;J<f.length;J+=1)for(let Q of Vj(f[J])){let Z=$.get(Q);if(Z)Z.add(J);else $.set(Q,new Set([J]))}return $}function JG(f,$){let J=$G(f),Q=new Set,Z=[$];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of Vj(f[W]))for(let H of J.get(j)??[])if(!Q.has(H))Z.push(H)}return Q}function s4(f,$,J,Q){let Z=P8(f.map((W)=>W.message),Q);for(let W=0;W<f.length&&Z>J;){if(!$(f[W])){W+=1;continue}let j=JG(f,W);Z-=Array.from(j).reduce((H,X)=>H+f[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,A)=>A-X))f.splice(H,1)}}function QG(f,$,J){let Q=P8(f.map((W)=>W.message),J);if(Q<=$)return;for(let W=f.length-1;W>=0&&Q>$;W-=1){let j=f[W];if(j.isFirstUser)continue;let H=Math.max(n3,j.estimatedTokens-(Q-$));if(H>=j.estimatedTokens)continue;Aj(f,W,Xj(j.message,H),J),Q=P8(f.map((X)=>X.message),J)}if(Q<=$)return;let Z=f.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,f[Z].estimatedTokens-(Q-$));Aj(f,Z,Xj(f[Z].message,W),J)}}function ZG(f,$){return JSON.stringify(f)!==JSON.stringify($)}function WG(f){let $=t4(f);if($<0||$===0&&!K8(f[0]))return{compactable:f,protectedTail:[]};return{compactable:f.slice(0,$),protectedTail:f.slice($)}}function Bj(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.maxInputTokens)),{compactable:J,protectedTail:Q}=WG(f.context.messages);if(J.length===0)return;let Z=oP(J,f.estimateMessageTokens);if(Z.length===0)return;s4(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,$,f.estimateMessageTokens),s4(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,$,f.estimateMessageTokens),s4(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,$,f.estimateMessageTokens),s4(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,$,f.estimateMessageTokens),QG(Z,$,f.estimateMessageTokens);let W=[...Z.map((X)=>X.message),...Q];if(!ZG(f.context.messages,W))return;let j=P8([...J.map((X)=>Yj(X)??X),...Q],f.estimateMessageTokens),H=P8(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:j,tokensAfter:H,targetTokens:$,maxInputTokens:f.context.maxInputTokens}),{messages:W}}function Kj(f){try{return JSON.stringify(f).length}catch{return String(f).length}}function jG(f){let $=0,J=0,Q=0;for(let Z of f){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=Kj(W.content);$+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:$,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var HG={basic:({context:f,estimateMessageTokens:$,logger:J})=>Bj({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>Hj({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??i9,f.triggerTokens):J?.preserveRecentTokens??i9,estimateMessageTokens:Z,logger:W})};function XG(f){if(typeof f.config.reserveTokens==="number"){let Q=Math.max(0,f.config.reserveTokens),Z=Math.max(0,f.maxInputTokens-Q);return{shouldCompact:f.inputTokens>Z,triggerTokens:Z,thresholdRatio:f.maxInputTokens>0?Z/f.maxInputTokens:0}}if(typeof f.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min(f.maxInputTokens-r3,f.maxInputTokens*r9));return{shouldCompact:f.inputTokens>Q,triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}let $=f.config.thresholdRatio??r9,J=f.maxInputTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function AG(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),Q=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:f.maxInputTokens>0?Q/f.maxInputTokens:0}}function G8(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let Q=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},Z=s3(),W=J?.strategy??"basic",j=HG[W],H=$.mode??"auto",X=J?.compact?"custom":W;return async(A)=>{let Y=A.apiMessages.reduce((D,y)=>D+Z(y),0),V=J?.maxInputTokens??A.model.info?.maxInputTokens??A.model.info?.contextWindow??p3;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=XG({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(f.logger?.debug("Context compaction diagnostics",{mode:H,strategy:W,iteration:A.iteration,providerId:f.providerId,modelId:f.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:A.messages.length,apiMessageCount:A.apiMessages.length,apiMessagesJsonChars:Kj(A.apiMessages),...jG(A.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?AG({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:$.manualTargetRatio}):B,P={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId,iteration:A.iteration,messages:A.messages,model:A.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?Y/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";A.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:A.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let G=A.messages.length,F=Date.now(),U=J?.compact?await J.compact(P):await j({context:P,providerConfig:{...Q,abortSignal:A.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:f.logger}),O=Date.now()-F,M=f.sessionId??A.conversationId,L={agentId:A.agentId,conversationId:A.conversationId,parentAgentId:A.parentAgentId??void 0};if(U?.messages){let D=U.messages.reduce((y,b)=>y+Z(b),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:V,inputTokens:Y,afterTokens:D,tokensSaved:Y-D,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(D/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length}),I4(f.telemetry,{ulid:M,strategy:X,mode:H,messagesBefore:G,messagesAfter:U.messages.length,messagesRemoved:G-U.messages.length,tokensBefore:Y,tokensAfter:D,tokensSaved:Y-D,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:f.providerId,modelId:f.modelId,...L})}else x4(f.telemetry,{ulid:M,strategy:X,mode:H,reason:"no_result",tokensBefore:Y,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:f.providerId,modelId:f.modelId,...L});return U}}var wH={};q(wH,{zodToJsonSchema:()=>kU,validateWithZod:()=>bU,resolveToolRoutingConfig:()=>p1,resolveToolPresetName:()=>hf,resolveCoreSelectedToolIds:()=>A6,getCoreHeadlessToolNames:()=>b8,getCoreDefaultEnabledToolIds:()=>X6,getCoreBuiltinToolCatalog:()=>r$,getCoreAcpToolNames:()=>Y6,createWindowsShellTool:()=>QQ,createWebFetchTool:()=>ZQ,createWebFetchExecutor:()=>S8,createToolPoliciesWithPreset:()=>J6,createSubmitAndExitTool:()=>XQ,createSkillsTool:()=>g$,createSearchTool:()=>$Q,createSearchExecutor:()=>C8,createReadFilesTool:()=>fQ,createFileReadExecutor:()=>w8,createEditorTool:()=>jQ,createEditorExecutor:()=>q8,createDefaultToolsWithPreset:()=>Q6,createDefaultTools:()=>W$,createDefaultExecutors:()=>d1,createBuiltinTools:()=>i$,createBashTool:()=>JQ,createBashExecutor:()=>N8,createAskQuestionTool:()=>HQ,createApplyPatchTool:()=>WQ,createApplyPatchExecutor:()=>M8,WebFetchRequestSchema:()=>o9,ToolPresets:()=>g0,TEAM_TOOL_NAMES:()=>i1,SubmitInputSchema:()=>z8,SkillsInputSchema:()=>O8,SearchCodebaseInputSchema:()=>R8,RunCommandsInputSchema:()=>v1,ReadFilesInputSchema:()=>U8,ReadFileRequestSchema:()=>wf,FetchWebContentInputSchema:()=>D8,EditFileInputSchema:()=>L8,DefaultToolNames:()=>B0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>l1,AskQuestionInputSchema:()=>T8,ApplyPatchInputSchema:()=>_8,ALL_DEFAULT_TOOL_NAMES:()=>J$});import{validateWithZod as bU,zodToJsonSchema as kU}from"@cline/shared";var B0={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"},J$=[B0.READ_FILES,B0.SEARCH_CODEBASE,B0.RUN_COMMANDS,B0.FETCH_WEB_CONTENT,B0.APPLY_PATCH,B0.EDITOR,B0.SKILLS,B0.ASK,B0.SUBMIT_AND_EXIT];_0();import{createTool as Cf,validateWithZod as Sf,zodToJsonSchema as Hf}from"@cline/shared";var Gj="__clineInternalTelemetry";function Fj(f){let $=f?.__clineInternalTelemetry;return $&&typeof $==="object"&&"capture"in $&&typeof $.capture==="function"?$:void 0}import{validateWithZod as YG}from"@cline/shared";import{z as _}from"zod";var Q$=6000,F8=_.string().describe("The absolute file path of a text file to read content from"),Uj=_.object({start_line:_.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:_.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"),wf=_.object({path:F8,start_line:Uj.shape.start_line,end_line:Uj.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),U8=_.object({files:_.array(wf).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.")}),Rj=_.union([U8,wf,_.array(wf),_.array(_.string()),_.string(),_.object({files:_.array(_.union([F8,wf]))}),_.object({files:wf}),_.object({files:F8}),_.object({file_paths:_.array(F8)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([F8,wf]))}),_.object({paths:wf}),_.object({paths:_.string()})]),R8=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),Dj=_.union([R8,_.array(_.string()),_.string(),_.object({queries:_.string()})]),x$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${Q$*2} characters) to avoid timeouts.`),v1=_.object({commands:_.array(x$).describe("Array of shell commands to execute")}),Lj=_.union([v1,_.object({commands:x$}),_.object({command:x$}),_.object({cmd:x$}),_.array(_.string()),_.string()]),t9=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),_j=_.union([x$,t9]),s9=_.object({commands:_.array(_j).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.")}),Oj=_.union([v1,s9,_.object({commands:_j}),_.array(t9),t9,_.object({command:x$}),_.object({cmd:x$}),_.array(_.string()),_.string()]),o9=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),D8=_.object({requests:_.array(o9).describe("Array of the URLs for the web fetch requests")}),L8=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.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 ${Q$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.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 ${Q$} 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:_.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."),_8=_.object({input:_.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."),Tj=_.union([_8,_.string()]),O8=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),T8=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),z8=_.object({summary:_.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:_.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.
|
|
85
|
+
${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function gF($){let f=await xF($.providerConfig),J="";for await(let Q of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function mF($){try{return JSON.stringify($).length}catch{return String($).length}}async function Sj($){let f=$.context.messages;if(f.length<2)return;let J=Mj(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let Q=f.slice(0,J),Z=Oj(Q),W=Z>=0?BQ(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let X=Tj(Q),Y=Uj(j),V=qj({previousSummary:W,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:W?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:jQ(V.length),newMessagesJsonChars:mF(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let B=await gF({providerConfig:wj({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!B.trim())return;let H=Nj(B,X),A=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[yj({summary:H,fileOps:X,tokensBefore:A}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function hj($){if(L8($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:VQ(J.content)}:J)}}function O8($,f){return $.reduce((J,Q)=>J+f(Q),0)}function Cj($,f){let J=Math.max(1,f),Q=Math.max(16,J*4);if(typeof $.content==="string"){let j=J$($.content,Q).trim();return{...$,content:j||"..."}}let Z=Q,W=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=J$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:W}}function vF($,f){let J=Lj($),Q=QJ($),Z=_j($),W=[];for(let j=0;j<$.length;j+=1){let X=hj($[j]);if(!X)continue;W.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function Ej($,f,J,Q){let Z=$[f];Z.message=J,Z.estimatedTokens=Q(J)}function cF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function uF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function bj($){return new Set([...cF($.message),...uF($.message)])}function dF($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let Q of bj($[J])){let Z=f.get(Q);if(Z)Z.add(J);else f.set(Q,new Set([J]))}return f}function lF($,f){let J=dF($),Q=new Set,Z=[f];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of bj($[W]))for(let X of J.get(j)??[])if(!Q.has(X))Z.push(X)}return Q}function ZJ($,f,J,Q){let Z=O8($.map((W)=>W.message),Q);for(let W=0;W<$.length&&Z>J;){if(!f($[W])){W+=1;continue}let j=lF($,W);Z-=Array.from(j).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(j).sort((Y,V)=>V-Y))$.splice(X,1)}}function pF($,f,J){let Q=O8($.map((W)=>W.message),J);if(Q<=f)return;for(let W=$.length-1;W>=0&&Q>f;W-=1){let j=$[W];if(j.isFirstUser)continue;let X=Math.max(Dj,j.estimatedTokens-(Q-f));if(X>=j.estimatedTokens)continue;Ej($,W,Cj(j.message,X),J),Q=O8($.map((Y)=>Y.message),J)}if(Q<=f)return;let Z=$.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,$[Z].estimatedTokens-(Q-f));Ej($,Z,Cj($[Z].message,W),J)}}function rF($,f){return JSON.stringify($)!==JSON.stringify(f)}function iF($){let f=QJ($);if(f<0||f===0&&!_8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function kj($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:Q}=iF($.context.messages);if(J.length===0)return;let Z=vF(J,$.estimateMessageTokens);if(Z.length===0)return;ZJ(Z,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,f,$.estimateMessageTokens),ZJ(Z,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,f,$.estimateMessageTokens),ZJ(Z,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,f,$.estimateMessageTokens),ZJ(Z,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,f,$.estimateMessageTokens),pF(Z,f,$.estimateMessageTokens);let W=[...Z.map((Y)=>Y.message),...Q];if(!rF($.context.messages,W))return;let j=O8([...J.map((Y)=>hj(Y)??Y),...Q],$.estimateMessageTokens),X=O8(W,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:W.length,messagesRemoved:$.context.messages.length-W.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:W}}function Ij($){try{return JSON.stringify($).length}catch{return String($).length}}function nF($){let f=0,J=0,Q=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=Ij(W.content);f+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var aF={basic:({context:$,estimateMessageTokens:f,logger:J})=>kj({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>Sj({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??YQ,$.triggerTokens):J?.preserveRecentTokens??YQ,estimateMessageTokens:Z,logger:W})};function sF($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min($.maxInputTokens-Fj,$.maxInputTokens*XQ));return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}let f=$.config.thresholdRatio??XQ,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function tF($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),Q=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}function M8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=zj(),W=J?.strategy??"basic",j=aF[W],X=f.mode??"auto",Y=J?.compact?"custom":W;return async(V)=>{let B=V.apiMessages.reduce((U,N)=>U+Z(N),0),H=J?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??Gj;if(typeof H!=="number"||!Number.isFinite(H)||H<=0)return;let A=sF({inputTokens:B,maxInputTokens:H,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:W,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:B,maxInputTokens:H,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:Ij(V.apiMessages),...nF(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?tF({inputTokens:B,maxInputTokens:H,autoTriggerTokens:A.triggerTokens,manualTargetRatio:f.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:H,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:H>0?B/H:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:H});let P=V.messages.length,F=Date.now(),D=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...Q,abortSignal:V.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),_=Date.now()-F,O=$.sessionId??V.conversationId,z={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(D?.messages){let U=D.messages.reduce((N,y)=>N+Z(y),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:H,inputTokens:B,afterTokens:U,tokensSaved:B-U,utilizationBefore:`${(B/H*100).toFixed(1)}%`,utilizationAfter:`${(U/H*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:D.messages.length,messagesRemoved:P-D.messages.length}),l6($.telemetry,{ulid:O,strategy:Y,mode:X,messagesBefore:P,messagesAfter:D.messages.length,messagesRemoved:P-D.messages.length,tokensBefore:B,tokensAfter:U,tokensSaved:B-U,triggerTokens:K.triggerTokens,maxInputTokens:H,thresholdRatio:K.thresholdRatio,durationMs:_,provider:$.providerId,modelId:$.modelId,...z})}else p6($.telemetry,{ulid:O,strategy:Y,mode:X,reason:"no_result",tokensBefore:B,triggerTokens:K.triggerTokens,maxInputTokens:H,thresholdRatio:K.thresholdRatio,durationMs:_,provider:$.providerId,modelId:$.modelId,...z});return D}}var ZY={};w(ZY,{zodToJsonSchema:()=>kR,validateWithZod:()=>bR,resolveToolRoutingConfig:()=>of,resolveToolPresetName:()=>b1,resolveCoreSelectedToolIds:()=>UJ,getCoreHeadlessToolNames:()=>p8,getCoreDefaultEnabledToolIds:()=>RJ,getCoreBuiltinToolCatalog:()=>r$,getCoreAcpToolNames:()=>zJ,createWindowsShellTool:()=>zQ,createWebFetchTool:()=>LQ,createWebFetchExecutor:()=>c8,createToolPoliciesWithPreset:()=>HJ,createSubmitAndExitTool:()=>TQ,createSkillsTool:()=>m$,createSearchTool:()=>RQ,createSearchExecutor:()=>v8,createReadFilesTool:()=>DQ,createFileReadExecutor:()=>m8,createEditorTool:()=>OQ,createEditorExecutor:()=>g8,createDefaultToolsWithPreset:()=>AJ,createDefaultTools:()=>j$,createDefaultExecutors:()=>sf,createBuiltinTools:()=>i$,createBashTool:()=>UQ,createBashExecutor:()=>I8,createAskQuestionTool:()=>MQ,createApplyPatchTool:()=>_Q,createApplyPatchExecutor:()=>x8,WebFetchRequestSchema:()=>KQ,ToolPresets:()=>c0,TEAM_TOOL_NAMES:()=>$2,SubmitInputSchema:()=>h8,SkillsInputSchema:()=>C8,SearchCodebaseInputSchema:()=>q8,RunCommandsInputSchema:()=>lf,ReadFilesInputSchema:()=>N8,ReadFileRequestSchema:()=>S1,FetchWebContentInputSchema:()=>w8,EditFileInputSchema:()=>y8,DefaultToolNames:()=>A0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>tf,AskQuestionInputSchema:()=>E8,ApplyPatchInputSchema:()=>S8,ALL_DEFAULT_TOOL_NAMES:()=>Q$});import{validateWithZod as bR,zodToJsonSchema as kR}from"@cline/shared";var A0={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"},Q$=[A0.READ_FILES,A0.SEARCH_CODEBASE,A0.RUN_COMMANDS,A0.FETCH_WEB_CONTENT,A0.APPLY_PATCH,A0.EDITOR,A0.SKILLS,A0.ASK,A0.SUBMIT_AND_EXIT];L0();import{createTool as C1,validateWithZod as E1,zodToJsonSchema as V1}from"@cline/shared";var gj="__clineInternalTelemetry";function mj($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{spawn as sj}from"node:child_process";import{StringDecoder as $P}from"node:string_decoder";import{getDefaultShell as fP,getShellArgs as JP}from"@cline/shared";import{validateWithZod as oF}from"@cline/shared";import{z as L}from"zod";var Z$=6000,T8=L.string().describe("The absolute file path of a text file to read content from"),vj=L.object({start_line:L.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),S1=L.object({path:T8,start_line:vj.shape.start_line,end_line:vj.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),N8=L.object({files:L.array(S1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),cj=L.union([N8,S1,L.array(S1),L.array(L.string()),L.string(),L.object({files:L.array(L.union([T8,S1]))}),L.object({files:S1}),L.object({files:T8}),L.object({file_paths:L.array(T8)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([T8,S1]))}),L.object({paths:S1}),L.object({paths:L.string()})]),q8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),uj=L.union([q8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),x$=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${Z$*2} characters) to avoid timeouts.`),lf=L.object({commands:L.array(x$).describe("Array of shell commands to execute")}),dj=L.union([lf,L.object({commands:x$}),L.object({command:x$}),L.object({cmd:x$}),L.array(L.string()),L.string()]),HQ=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),lj=L.union([x$,HQ]),AQ=L.object({commands:L.array(lj).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.")}),pj=L.union([lf,AQ,L.object({commands:lj}),L.array(HQ),HQ,L.object({command:x$}),L.object({cmd:x$}),L.array(L.string()),L.string()]),KQ=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),w8=L.object({requests:L.array(KQ).describe("Array of the URLs for the web fetch requests")}),y8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${Z$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${Z$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:L.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),S8=L.object({input:L.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),rj=L.union([S8,L.string()]),C8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),E8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),h8=L.object({summary:L.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:L.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
|
|
86
86
|
'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
|
|
87
|
-
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
|
|
87
|
+
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 W$($){if($ instanceof Error)return $.message;return String($)}function ij($){if(typeof $.old_text==="string"&&$.old_text.length>Z$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${Z$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>Z$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${Z$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class g$ extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function Y1($,f,J){return Promise.race([$,new Promise((Q,Z)=>{setTimeout(()=>Z(new g$(J,f)),f)})])}function WJ($){let{path:f,start_line:J,end_line:Q}=$;if(J==null&&Q==null)return f;return`${f}:${J??1}-${Q??"EOF"}`}function nj($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function aj($){let f=oF(pj,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function eF($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${J.join(" ")}`}var GQ=200;function FQ($){let f=eF($);if(f.length<=GQ)return f;let J=f.length-GQ;return`${f.slice(0,GQ)} ... [command truncated: ${J} more chars; full command is in the tool call input]`}var b8=48000,pf=2000,PQ=2000,jJ=48000,rf=48000;class k8 extends Error{exitCode;output;constructor($,f){super(`Command exited with code ${$}`);this.exitCode=$;this.output=f;this.name="CommandExitError"}}function tj($){let f=Math.ceil($/2),J=Math.max(1,$-f),Q=new $P("utf8"),Z="",W="",j=0,X=(Y)=>{if(!Y)return;j+=Y.length;let V=f-Z.length;if(V>0){Z+=Y.slice(0,V),W=(W+Y.slice(V)).slice(-J);return}W=(W+Y).slice(-J)};return{append(Y){X(Q.write(Y))},snapshot(){return X(Q.end()),{text:Z+W,totalChars:j,dropped:j>Z.length+W.length}}}}function oj($,f,J){let Q=Math.ceil(f/2),Z=Math.max(1,f-Q);return`${$.slice(0,Q)}
|
|
88
|
+
[... output truncated: ${J} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
|
|
89
|
+
`+$.slice(-Z)}function QP($,f,J,Q,Z){return new Promise((W,j)=>{let X=process.platform==="win32",Y=sj($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,B=tj(Q),H=tj(Q),A=!1,K=!1,G=(O)=>{if(K)return;K=!0,O()},R=()=>{if(!V)return;if(X){sj("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},P=(O)=>{A=!0,R(),G(()=>j(O))},F=setTimeout(()=>P(new g$(`Command timed out after ${J}ms`,J)),J),D=()=>P(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",D);let _=()=>{clearTimeout(F),f.signal?.removeEventListener("abort",D)};Y.stdout?.on("data",(O)=>{B.append(O)}),Y.stderr?.on("data",(O)=>{H.append(O)}),Y.on("close",(O)=>{if(_(),A)return;let z=B.snapshot(),U=H.snapshot();if(O!==0){let N=O??1,y=Z?z.text+(U.text?`
|
|
90
|
+
[stderr]
|
|
91
|
+
${U.text}`:""):z.text,h=z.dropped||Z&&U.dropped,u=Z?z.totalChars+U.totalChars:z.totalChars;if(h||y.length>Q)y=oj(y,Q,u);let t=y.length>0?`[Command exited with code ${N}]
|
|
92
|
+
${y}`:`[Command exited with code ${N}]`;G(()=>j(new k8(N,t)))}else{let N=Z?z.text+(U.text?`
|
|
93
|
+
[stderr]
|
|
94
|
+
${U.text}`:""):z.text;if(z.dropped||Z&&U.dropped||N.length>Q){let h=Z?z.totalChars+U.totalChars:z.totalChars;N=oj(N,Q,h)}G(()=>W(N))}}),Y.on("error",(O)=>{_(),G(()=>j(Error(`Failed to execute command: ${O.message}`)))})})}function I8($={}){let{shell:f=fP(process.platform),timeoutMs:J=30000,env:Q={},combineOutput:Z=!0}=$,W=$.maxOutputChars??$.maxOutputBytes??b8;return(j,X,Y)=>{let V=typeof j!=="string";return QP({executable:V?j.command:f,args:V?j.args??[]:JP(f,j),cwd:X,env:Q},Y,J,W,Z)}}function ej($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function $X($,f){I3(mj($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:ej($,"mode"),source:ej($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function ZP($){let f=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return f?.[1]??f?.[2]??f?.[3]}function WP($){let f=[];for(let J=0;J<$.length;J+=1){let Q=$[J],Z=ZP(Q);if(!Z){f.push(Q);continue}let W=$.findIndex((X,Y)=>Y>J&&X.trim()===Z);if(W===-1){f.push(Q);continue}let j=[Q];while(J<W){J+=1;let X=$[J];j.push(X)}f.push(j.join(`
|
|
95
|
+
`))}return f}function DQ($,f={}){let J=f.fileReadTimeoutMs??1e4;return C1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${pf} lines / ~${Math.round(jJ/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:V1(N8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=E1(cj,Q),j;if(typeof W==="string")j=[{path:W}];else if(Array.isArray(W))j=W.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in W)j=(Array.isArray(W.files)?W.files:[W.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in W)j=(Array.isArray(W.file_paths)?W.file_paths:[W.file_paths]).map((Y)=>({path:Y}));else if("paths"in W)j=(Array.isArray(W.paths)?W.paths:[W.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else j=[W];return Promise.all(j.map(async(X)=>{let Y=nj(X);if(Y)return{query:WJ(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await Y1($(X,Z),J,`File read timed out after ${J}ms`);return{query:WJ(X),result:V,success:!0}}catch(V){let B=W$(V);return{query:WJ(X),result:"",error:`Error reading file: ${B}`,success:!1}}}))}})}function RQ($,f={}){let J=f.searchTimeoutMs??30000,Q=f.cwd??process.cwd();return C1({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(rf/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:V1(q8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=E1(uj,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(Y)=>{try{let V=await Y1($(Y,Q,W),J,`Search timed out after ${J}ms`);return{query:Y,result:V,success:!0}}catch(V){let B=W$(V);return{query:Y,result:"",error:`Search failed: ${B}`,success:!1}}}))}})}function UQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return C1({name:"run_commands",description:`Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round(b8/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:V1(lf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=E1(dj,W),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=WP(Y),Promise.all(Y.map(async(V)=>{let B=Date.now(),H=FQ(V);try{let A=await Y1($(V,Z,j),J,`Command timed out after ${J}ms`);return{query:H,result:A,success:!0}}catch(A){if(A instanceof g$)$X(j,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Q,commandCount:Y.length,durationMs:Date.now()-B});if(A instanceof k8)return{query:H,result:A.output,error:A.message,success:!1};let K=W$(A);return{query:H,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function zQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return C1({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. Output beyond ~${Math.round(b8/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:V1(AQ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=aj(W);return Promise.all(X.map(async(Y)=>{let V=Date.now(),B=FQ(Y);try{let H=await Y1($(Y,Z,j),J,`Command timed out after ${J}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof g$)$X(j,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:Q,commandCount:X.length,durationMs:Date.now()-V});if(H instanceof k8)return{query:B,result:H.output,error:H.message,success:!1};let A=W$(H);return{query:B,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function LQ($,f={}){let J=f.webFetchTimeoutMs??30000;return C1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:V1(w8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=E1(w8,Q);return Promise.all(W.requests.map(async(j)=>{try{let X=await Y1($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let Y=W$(X);return{query:j.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var jP=`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:
|
|
88
96
|
|
|
89
97
|
*** Begin Patch
|
|
90
98
|
*** Update File: path/to/file.ts
|
|
@@ -120,126 +128,126 @@ Example:
|
|
|
120
128
|
</div>
|
|
121
129
|
);
|
|
122
130
|
}
|
|
123
|
-
*** End Patch`;function
|
|
124
|
-
`),Z=0,W=[
|
|
125
|
-
${this.lines[this.index]}`);if(
|
|
126
|
-
`);this.addWarning({path:this.currentPath
|
|
127
|
-
`),chunks:[]}}}function
|
|
128
|
-
`));for(let
|
|
129
|
-
`));if(
|
|
130
|
-
`)),
|
|
131
|
-
`));if(
|
|
132
|
-
`)),
|
|
133
|
-
`));if(
|
|
134
|
-
`)),
|
|
135
|
-
`).map((
|
|
136
|
-
`),Z=[],W=0;for(let j of
|
|
137
|
-
`)}async function
|
|
138
|
-
`)}return W}function
|
|
139
|
-
|
|
140
|
-
[
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
`),Z
|
|
145
|
-
`
|
|
146
|
-
`)
|
|
147
|
-
|
|
148
|
-
`),j=W.
|
|
149
|
-
`)
|
|
150
|
-
|
|
151
|
-
`),G=
|
|
152
|
-
`)}return
|
|
153
|
-
`)
|
|
154
|
-
`)
|
|
155
|
-
|
|
156
|
-
`)
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(
|
|
131
|
+
*** End Patch`;function _Q($,f={}){let J=f.applyPatchTimeoutMs??30000,Q=f.cwd??process.cwd();return C1({name:"apply_patch",description:jP,inputSchema:V1(S8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=E1(rj,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await Y1($({input:X},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${W$(Y)}`,success:!1}}}})}function OQ($,f={}){let J=f.editorTimeoutMs??30000,Q=f.cwd??process.cwd();return C1({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:V1(y8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=E1(y8,Z),X=j.insert_line==null?"edit":"insert",Y=ij(j);if(Y)return{query:`${X}:${j.path}`,result:"",error:Y,success:!1};try{let V=await Y1($(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:V,success:!0}}catch(V){let B=W$(V);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${B}`,success:!1}}}})}function m$($,f={}){let J=f.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=C1({name:"skills",description:Q,inputSchema:V1(C8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=E1(C8,W);return Y1($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(W&&W.length>0)return`${Q} Available skills: ${W.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),Z}function MQ($){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:V1(E8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let Q=E1(E8,f);return $(Q.question,Q.options,J)}}}function TQ($,f={}){let J=f.submitTimeoutMs??15000;return C1({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:V1(h8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=E1(h8,Q);return Y1($(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function j$($){let{executors:f,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:B=!1,...H}=$,A=[];if(J&&f.readFile)A.push(DQ(f.readFile,H));if(Q&&f.search)A.push(RQ(f.search,H));if(Z&&f.bash)if(process.platform==="win32")A.push(zQ(f.bash,H));else A.push(UQ(f.bash,H));if(W&&f.webFetch)A.push(LQ(f.webFetch,H));if(X&&f.editor)A.push(OQ(f.editor,H));else if(j&&f.applyPatch)A.push(_Q(f.applyPatch,H));if(Y&&f.skills)A.push(m$(f.skills,H));let K=B?f.submit:void 0;if(V&&f.askQuestion&&!K)A.push(MQ(f.askQuestion));if(K)A.push(TQ(K,H));return A}import*as m0 from"node:fs/promises";import*as v0 from"node:path";var d={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},JX=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor($){super($);this.name="DiffError"}}function g0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class NQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(d.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(d.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(d.UPDATE)){this.parseUpdate($.substring(d.UPDATE.length).trim());return}if($?.startsWith(d.DELETE)){this.parseDelete($.substring(d.DELETE.length).trim());return}if($?.startsWith(d.ADD)){this.parseAdd($.substring(d.ADD.length).trim());return}throw new Z0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new Z0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(d.MOVE)?(this.lines[this.index++]??"").substring(d.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",Q=this.parseUpdateFile(J,$);Q.movePath=f,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},Q=$.split(`
|
|
132
|
+
`),Z=0,W=[d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(!W.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],X=j?.startsWith("@@ ")?j.substring(3):void 0;if(X!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new Z0(`Invalid Line:
|
|
133
|
+
${this.lines[this.index]}`);if(X?.trim()){let P=g0(X.trim());for(let F=Z;F<Q.length;F++){let D=Q[F];if(D&&(g0(D)===P||g0(D.trim())===P)){if(Z=F+1,g0(D.trim())===P&&g0(D)!==P)this.fuzz++;break}}}let[V,B,H,A]=VP(this.lines,this.index),[K,G,R]=YP(Q,V,Z,A);if(K===-1){let P=V.join(`
|
|
134
|
+
`);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=H}else{this.fuzz+=G;for(let P of B)P.origIndex+=K,J.chunks.push(P);Z=K+V.length,this.index=H}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new Z0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new Z0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[d.END,d.UPDATE,d.DELETE,d.ADD];while(this.hasMoreLines()&&!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new Z0(`Invalid Add File line (missing '+'): ${Q}`);f.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
|
|
135
|
+
`),chunks:[]}}}function fX($,f){let J=$.length>f.length?$:f,Q=$.length>f.length?f:$;if(J.length===0)return 1;let Z=XP(Q,J);return(J.length-Z)/J.length}function XP($,f){let J=f.length+1,Q=$.length+1,Z=Array(J*Q).fill(0),W=(X,Y)=>Z[X*Q+Y]??0,j=(X,Y,V)=>{Z[X*Q+Y]=V};for(let X=0;X<=f.length;X++)j(X,0,X);for(let X=0;X<=$.length;X++)j(0,X,X);for(let X=1;X<=f.length;X++)for(let Y=1;Y<=$.length;Y++)if(f[X-1]===$[Y-1])j(X,Y,W(X-1,Y-1));else j(X,Y,1+Math.min(W(X-1,Y-1),W(X,Y-1),W(X-1,Y)));return W(f.length,$.length)}function YP($,f,J,Q){if(f.length===0)return[J,0,1];let Z=0,W=(j)=>{let X=g0(f.join(`
|
|
136
|
+
`));for(let V=j;V<$.length;V++){let B=g0($.slice(V,V+f.length).join(`
|
|
137
|
+
`));if(B===X)return[V,0,1];let H=fX(B,X);if(H>Z)Z=H}for(let V=j;V<$.length;V++){let B=g0($.slice(V,V+f.length).map((A)=>A.trimEnd()).join(`
|
|
138
|
+
`)),H=g0(f.map((A)=>A.trimEnd()).join(`
|
|
139
|
+
`));if(B===H)return[V,1,1]}for(let V=j;V<$.length;V++){let B=g0($.slice(V,V+f.length).map((A)=>A.trim()).join(`
|
|
140
|
+
`)),H=g0(f.map((A)=>A.trim()).join(`
|
|
141
|
+
`));if(B===H)return[V,100,1]}let Y=0.66;for(let V=j;V<$.length;V++){let B=g0($.slice(V,V+f.length).join(`
|
|
142
|
+
`)),H=fX(B,X);if(H>=Y)return[V,1000,H];if(H>Z)Z=H}return[-1,0,Z]};if(Q){let[j,X,Y]=W($.length-f.length);if(j!==-1)return[j,X,Y];return[j,X,Y]=W(J),[j,X+1e4,Y]}return W(J)}function VP($,f){let J=f,Q=[],Z=[],W=[],j=[],X="keep",Y=["@@",d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(J<$.length){let V=$[J];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new Z0(`Invalid line: ${V}`);J++;let B=X,H=V;if(H[0]==="+")X="add";else if(H[0]==="-")X="delete";else if(H[0]===" ")X="keep";else X="keep",H=` ${H}`;if(H=H.slice(1),X==="keep"&&B!==X){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(X==="delete")Z.push(H),Q.push(H);else if(X==="add")W.push(H);else Q.push(H)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<$.length&&$[J]===d.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function qQ($,f,J){let Q=v0.isAbsolute(f),Z=Q?v0.normalize(f):v0.resolve($,f);if(!J||Q)return Z;let W=v0.relative($,Z);if(W.startsWith("..")||v0.isAbsolute(W))throw new Z0(`Path must stay within cwd: ${f}`);return Z}function BP($){return $.split(`
|
|
143
|
+
`).map((f)=>f.replace(/\r$/,""))}function QX($){if($.trim()==="")return!1;return JX.some((f)=>$.startsWith(f))}function HP($){let f=0,J=$.length;while(f<J&&QX($[f]??""))f++;while(J>f&&QX($[J-1]??""))J--;return $.slice(f,J)}function AP($){let f=BP($),J=f.findIndex((j)=>j.startsWith(d.BEGIN)),Q=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(d.END)){Q=j;break}if(J!==-1||Q!==-1){if(J===-1||Q===-1||Q<J)throw new Z0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,Q+1)}}let Z=HP(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[d.BEGIN,...Z,d.END]}}function KP($,f){let J=new Set;for(let Q of $)for(let Z of f)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function GP($,f,J){if(f.length===0)return $;let Q=$.split(`
|
|
144
|
+
`),Z=[],W=0;for(let j of f){if(j.origIndex>Q.length)throw new Z0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${Q.length}`);if(W>j.origIndex)throw new Z0(`${J}: currentIndex ${W} > chunk.origIndex ${j.origIndex}`);Z.push(...Q.slice(W,j.origIndex)),Z.push(...j.insLines),W=j.origIndex+j.delLines.length}return Z.push(...Q.slice(W)),Z.join(`
|
|
145
|
+
`)}async function FP($,f,J,Q){let Z=KP($,[d.UPDATE,d.DELETE]),W={};for(let j of Z){let X=qQ(f,j,Q),Y;try{Y=await m0.readFile(X,J)}catch{throw new Z0(`File not found: ${j}`)}W[j]=Y.replace(/\r\n/g,`
|
|
146
|
+
`)}return W}function PP($,f){let J={};for(let[Q,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:f[Q]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[Q]={type:"add",newContent:Z.newFile};break;case"update":J[Q]={type:"update",oldContent:f[Q],newContent:GP(f[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}function DP($){let f=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let J of $){let Q=J.chunkIndex===void 0?"unknown":String(J.chunkIndex+1);if(f.push(`${J.path}: hunk ${Q}: ${J.message}`),J.context)f.push(`Context:
|
|
147
|
+
${J.context}`)}return f.join(`
|
|
148
|
+
`)}async function RP($,f,J,Q){let Z=[];for(let[W,j]of Object.entries($)){let X=qQ(f,W,Q);switch(j.type){case"delete":await m0.rm(X,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${W} with no content`);await m0.mkdir(v0.dirname(X),{recursive:!0}),await m0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${W} has no new content`);if(j.movePath){let Y=qQ(f,j.movePath,Q);await m0.mkdir(v0.dirname(Y),{recursive:!0}),await m0.writeFile(Y,j.newContent,{encoding:J}),await m0.rm(X,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await m0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function x8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(Q,Z,W)=>{let j=AP(Q.input),X=await FP(j.lines,Z,f,J),Y=new NQ(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new Z0(DP(V.warnings));let H=PP(V,X),A=await RP(H,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of A)K.push(G);if(B>0)K.push(`Note: Patch applied with fuzz factor ${B}`);return K.join(`
|
|
149
|
+
`)}}import*as Q1 from"node:fs/promises";import*as J1 from"node:path";function UP($,f,J){let Q=J1.isAbsolute(f),Z=Q?J1.normalize(f):J1.resolve($,f);if(!J)return Z;if(Q)return Z;let W=J1.relative($,Z);if(W.startsWith("..")||J1.isAbsolute(W))throw Error(`Path must stay within cwd: ${f}`);return Z}function zP($,f){if(f.length===0)return 0;return $.split(f).length-1}function LP($,f,J){let Q=$.split(`
|
|
150
|
+
`),Z=f.split(`
|
|
151
|
+
`),W=Math.max(Q.length,Z.length),j=["```diff"],X=0;for(let Y=0;Y<W;Y++){if(X>=J){j.push("... diff truncated ...");break}let V=Q[Y],B=Z[Y];if(V===B)continue;let H=Y+1;if(V!==void 0)j.push(`-${H}: ${V}`),X++;if(B!==void 0&&X<J)j.push(`+${H}: ${B}`),X++}return j.push("```"),j.join(`
|
|
152
|
+
`)}async function _P($,f,J){return await Q1.mkdir(J1.dirname($),{recursive:!0}),await Q1.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function OP($){try{return await Q1.access($),!0}catch{return!1}}async function MP($,f,J,Q,Z){let W=await Q1.readFile($,Q),j=zP(W,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=W.replace(f,J??"");await Q1.writeFile($,X,{encoding:Q});let Y=LP(W,X,Z);return`Edited ${$}
|
|
153
|
+
${Y}`}async function TP($,f,J,Q){let W=(await Q1.readFile($,Q)).split(`
|
|
154
|
+
`),j=W.length+1;if(f<1||f>j)throw Error(`Invalid insert_line: ${f}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let X=f-1;return W.splice(X,0,...J.split(`
|
|
155
|
+
`)),await Q1.writeFile($,W.join(`
|
|
156
|
+
`),{encoding:Q}),`Inserted content at line ${f} in ${$}.`}function g8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=$;return async(Z,W,j)=>{let X=UP(W,Z.path,J);if(Z.insert_line!=null)return TP(X,Z.insert_line,Z.new_text,f);if(!await OP(X))return _P(X,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return MP(X,Z.old_text,Z.new_text,f,Q)}}import{createReadStream as NP}from"node:fs";import*as XJ from"node:fs/promises";import*as X$ from"node:path";import{createInterface as qP}from"node:readline";import{resolveExistingFilePath as wP}from"@cline/shared/storage";var yP=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),SP={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},ZX=1e8,CP=50000;function WX($){let{reason:f}=$;if(f instanceof Error)return f;if(f!==void 0)return Error(String(f));return Error("File read was aborted")}async function EP($,f,J,Q,Z,W){if(W?.aborted)throw WX(W);let j=Math.max(Q??1,1),X=Z??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:j+CP-1,B=[],H=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,j+pf-1):j+pf-1,P=J?String(R).length+3:0,F=NP($,{encoding:f}),D=qP({input:F,crlfDelay:Number.POSITIVE_INFINITY}),_=W?()=>F.destroy(WX(W)):void 0;if(W&&_)W.addEventListener("abort",_,{once:!0});try{for await(let h of D){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<j||K)continue;if(B.length>=pf){K=!0;continue}let u=h;if(u.length>PQ)u=`${u.slice(0,PQ)} [line truncated]`;let t=H+u.length+P+1;if(t>jJ&&B.length>0){K=!0;continue}B.push({lineNumber:A,text:u}),H=t}}finally{if(W&&_)W.removeEventListener("abort",_);D.close(),F.destroy()}let O=String(B[B.length-1]?.lineNumber??A).length,z=B.map(({lineNumber:h,text:u})=>J?`${String(h).padStart(O," ")} | ${u}`:u).join(`
|
|
157
|
+
`),U=B[B.length-1]?.lineNumber;if(U===void 0)return z;let N=Math.min(X,A);if(U>=N)return z;let y=G?`${A}+ lines`:N;return`${z}
|
|
158
|
+
|
|
159
|
+
[Showing lines ${j}-${U} of ${y}. Use start_line/end_line to read other sections.]`}function m8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:Q}={...SP,...$};return async(Z,W)=>{let{path:j,start_line:X,end_line:Y}=Z,V=X$.isAbsolute(j)?X$.normalize(j):X$.resolve(process.cwd(),j),B=wP(V)??V,H=X$.extname(B).toLowerCase(),A=yP.get(H),K=await XJ.stat(B);if(!K.isFile())throw Error(`Path is not a file: ${B}`);if(A){if(K.size>f)throw Error(`Image file too large: ${K.size} bytes (max: ${f} bytes).`);if(W.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await XJ.readFile(B);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>ZX)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${ZX} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return EP(B,J,Q,X,Y,W.signal)}}import{spawn as KX}from"node:child_process";import*as GX from"node:fs/promises";import*as BJ from"node:path";var HX={};w(HX,{prewarmFileIndex:()=>VJ,getFileIndex:()=>h1,enrichPromptWithMentions:()=>af});import{spawn as hP}from"node:child_process";import{readdir as bP}from"node:fs/promises";import yQ from"node:path";import{isMainThread as YX,parentPort as jX,Worker as kP}from"node:worker_threads";var IP=15000,xP=600000,gP=1000,mP=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function XX($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var nf=new Map;function vP(){if(!YX)return!1;return!0}function cP($){if(nf.size<=1)return;for(let[f,J]of nf.entries()){if(J.pending)continue;if($-J.lastAccessedAt>xP)nf.delete(f)}}function uP($,f){return yQ.relative($,f).split(yQ.sep).join("/")}async function dP($){let J=(await new Promise((Q,Z)=>{let W=hP("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),j="",X="";W.stdout.on("data",(Y)=>{j+=Y.toString()}),W.stderr.on("data",(Y)=>{X+=Y.toString()}),W.on("error",Z),W.on("close",(Y)=>{if(Y===0){Q(j);return}Z(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function VX($,f,J){let Q;try{Q=await bP(f,{withFileTypes:!0})}catch(Z){if(XX(Z))return;throw Z}for(let Z of Q){let W=yQ.join(f,Z.name);if(Z.isDirectory()){if(mP.has(Z.name))continue;try{await VX($,W,J)}catch(j){if(XX(j))continue;throw j}continue}if(Z.isFile())J.add(uP($,W))}}async function lP($){let f=new Set;return await VX($,$,f),f}async function YJ($){try{return await dP($)}catch{return lP($)}}function pP(){if(YX||!jX)return;let $=jX;$.on("message",(f)=>{if(f.type!=="index")return;YJ(f.cwd).then((J)=>{let Q={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(Q)})})}class BX{worker=new kP(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},gP);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),W(X)}})}),Q={type:"index",requestId:f,cwd:$};return this.worker.postMessage(Q),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}pP();var wQ;function rP(){if(!vP())return null;if(wQ===void 0)wQ=new BX;return wQ}async function iP($){let f=rP();if(!f)return YJ($);try{let J=await f.requestIndex($);if(J===null)return YJ($);return new Set(J)}catch{return YJ($)}}async function h1($,f={}){let J=f.ttlMs??IP,Q=Date.now();cP(Q);let Z=nf.get($);if(Z&&J>0&&Q-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=Q,Z.files;if(Z?.pending)return Z.lastAccessedAt=Q,Z.pending;let W=iP($).then((j)=>{return nf.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return nf.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function VJ($,f={}){await h1($,{...f,ttlMs:0})}import{stat as nP}from"node:fs/promises";import v$ from"node:path";var aP=/[),.:;!?`'"]+$/,sP=/^[(`'"]+/;function tP($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of f){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(sP,"").replace(aP,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function oP($,f){let J=$.replace(/\\/g,"/"),Q=v$.isAbsolute(J)?v$.resolve(J):v$.resolve(f,J),Z=v$.relative(f,Q);if(Z.startsWith("..")||v$.isAbsolute(Z))return;return Z.split(v$.sep).join("/")}async function af($,f,J={}){let Q=tP($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,X=await h1(f,{ttlMs:J.ttlMs}),Y=[],V=[],B=[],H=0;for(let A of Q){if(Z&&B.length>=Z){V.push(A);continue}let K=oP(A,f);if(!K||!X.has(K)){V.push(A);continue}if(!W||!j){Y.push(K);continue}let G=v$.join(f,K);try{if(!(await nP(G)).isFile()){V.push(A);continue}let P=H+W;if(P>j){V.push(A);continue}H=P,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Q,matchedFiles:Y,ignoredMentions:V}}var eP=["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"],$D=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],c$=null;function fD(){if(c$!==null)return Promise.resolve(c$);return new Promise(($)=>{let f=KX("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});f.on("close",(J)=>{c$=J===0,$(c$)}),f.on("error",()=>{c$=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(c$===null)c$=!1,$(!1)},1000)})}function JD($,f,J,Q,Z=5000,W){return new Promise((j)=>{let X=KX("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,B=()=>{if(!X.killed)X.kill("SIGTERM")},H=setTimeout(()=>{if(!V)V=!0,B(),j(null)},Z),A=(K)=>{if(!V)V=!0,clearTimeout(H),B(),j(K)};if(W?.aborted){B(),j(null);return}W?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
|
|
160
|
+
`).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let F=JSON.parse(P);if(F.type==="match"){let D=F.data,_=[];if(F.data.submatches&&F.data.submatches.length>0){let O=F.data.submatches[0];G.push({file:D.path.text,line:D.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:_})}}else if(F.type==="context"&&G.length>0){let D=G[G.length-1],_=F.data.line_number===D.line?">":" ";D.context.push(`${_} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function QD($,f,J,Q){let Z=$.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let Y=0;Y<Z.length-1;Y++)if(f.has(Z[Y]??""))return!1;let X=BJ.posix.extname(W).slice(1).toLowerCase();return J.has(X)||!X&&!W.startsWith(".")}function v8($={}){let{includeExtensions:f=eP,excludeDirs:J=$D,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=$,j=new Set(J),X=new Set(f.map((Y)=>Y.toLowerCase()));return async(Y,V,B)=>{if(B.signal?.aborted)throw Error("Search operation aborted");let H=await fD(),A=null;if(H)A=await JD(Y,V,Q,Z,5000,B.signal);if(A){let D=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let _ of A)D.push(`${_.file}:${_.line}:${_.column}`),D.push(..._.context),D.push("");if(A.length>=Q)D.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return AX(D.join(`
|
|
161
|
+
`))}let K;try{K=new RegExp(Y,"gim")}catch(D){throw Error(`Invalid regex pattern: ${Y}. ${D instanceof Error?D.message:""}`)}let G=[],R=0,P=await h1(V);for(let D of P){if(B.signal?.aborted)throw Error("Search operation aborted");if(!QD(D,j,X,W))continue;if(G.length>=Q)break;R++;let _=BJ.join(V,D);try{let z=(await GX.readFile(_,"utf-8")).split(`
|
|
162
|
+
`);for(let U=0;U<z.length;U++){let N=z[U];K.lastIndex=0;let y=K.exec(N);while(y!==null){if(G.length>=Q)break;let h=Math.max(0,U-Z),u=Math.min(z.length-1,U+Z),t=[];for(let f0=h;f0<=u;f0++){let o=f0===U?">":" ";t.push(`${o} ${f0+1}: ${z[f0]}`)}if(G.push({file:D,line:U+1,column:y.index+1,match:y[0],context:t}),y.index===K.lastIndex)K.lastIndex++;y=K.exec(N)}}}catch{}}if(G.length===0)return`No results found for pattern: ${Y}
|
|
163
|
+
Searched ${R} files.`;let F=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let D of G)F.push(`${D.file}:${D.line}:${D.column}`),F.push(...D.context),F.push("");if(G.length>=Q)F.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return AX(F.join(`
|
|
164
|
+
`))}}function AX($){if($.length<=rf)return $;let f=Math.ceil(rf/2),J=Math.max(1,rf-f);return`${$.slice(0,f)}
|
|
165
|
+
[... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
|
|
166
|
+
`+$.slice(-J)}function ZD($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
|
|
167
|
+
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(f,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
160
168
|
`).replace(/\n{3,}/g,`
|
|
161
169
|
|
|
162
|
-
`).trim()}function
|
|
163
|
-
[Content truncated: showing first 50000 of ${
|
|
164
|
-
`)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function d1(f={}){return{readFile:w8(f.fileRead),search:C8(f.search),bash:N8(f.bash),webFetch:S8(f.webFetch),applyPatch:M8(f.applyPatch),editor:q8(f.editor)}}var XF={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"},l1=[{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 cj(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((Q)=>J.includes(Q.toLowerCase()))}function AF(f,$,J,Q){if(f.mode&&f.mode!=="any"&&f.mode!==Q)return!1;return cj($,f.providerIdIncludes)&&cj(J,f.modelIdIncludes)}function p1(f,$,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!AF(j,f,$,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let W={};for(let[j,H]of Z.entries())W[XF[j]]=H;return W}var g0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function hf(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function J6(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let Q of J$)J[Q]=$;return J}function Q6(f,$){let J=g0[f],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return W$({...W,...$})}import{createTool as VU,zodToJsonSchema as BU}from"@cline/shared";import{z as OQ}from"zod";import{createAgentRuntime as JU}from"@cline/agents";import{createContributionRegistry as QU}from"@cline/shared";import{createGateway as DF,createHandlerAsync as LF,hasRegisteredHandler as _F,MODEL_COLLECTIONS_BY_PROVIDER_ID as OF,normalizeProviderId as TF}from"@cline/llms";import{EMPTY_CONTENT_TEXT as YF}from"@cline/shared";function VF(f){let $=KF(f.content),J=[],Q=f.id??FF(),Z=0,W=[],j=()=>{if(W.length===0)return;let H=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:H,role:f.role,content:W.map(PF),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:uj(f.metrics)}),W=[]};if($.length===0)return J.push({id:Q,role:f.role,content:[{type:"text",text:YF}],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:uj(f.metrics)}),J;for(let H of $){if(H.type!=="tool_result"){W.push(H);continue}j(),J.push({id:`${Q}_tool_${H.tool_use_id}`,role:"tool",content:[lj(H)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return j(),J}function Z6(f){return f.flatMap(VF)}function BF(f){let $=f.content.map(pj).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:GF(f.metrics)}}function r1(f){return f.map(BF)}function W6(f){let $=[];for(let J of f){let Q=J.content.map(pj).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=$[$.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}$.push({role:Z,content:Q})}return $}function KF(f){if(typeof f==="string")return f.trim().length>0?[{type:"text",text:f}]:[];return[...f]}function PF(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 lj(f)}}function lj(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:f.name,output:f.content,isError:f.is_error}}function pj(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":{let $=f.metadata;return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:$?.thoughtSignature??$?.signature}}case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,name:f.toolName,content:J,is_error:f.isError}}}}function uj(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 GF(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var dj=0;function FF(){return dj+=1,`msg_${Date.now().toString(36)}_${dj.toString(36)}`}function UF(f){switch(f.type){case"text":return[{type:"text-delta",text:f.text}];case"reasoning":return[{type:"reasoning-delta",text:f.reasoning,metadata:f.signature?{thoughtSignature:f.signature,details:f.details}:{details:f.details}}];case"tool_calls":{let $=f.tool_call.function,J=$.arguments;return[{type:"tool-call-delta",toolCallId:f.tool_call.call_id??$.id,toolName:$.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...f.signature?{metadata:{thoughtSignature:f.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost}}];case"done":return[{type:"finish",reason:RF(f),error:f.error}];default:return[]}}function RF(f){if(f.success===!1)return"error";if(f.incompleteReason==="max_output_tokens"||f.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function rj(f){return{async*stream($){let J=!1,Q=!1;try{let Z=typeof f==="function"?await f():f;Z.setAbortSignal?.($.signal);let W=W6($.messages),j=$.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage($.systemPrompt??"",W,j))for(let X of UF(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")Q=!0;yield X}if(!J)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:$.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function zF(f){let $=Object.fromEntries(Object.entries(f).filter(([,J])=>J!==void 0));return Object.keys($).length>0?$:void 0}function MF(f){return f.providerId==="openai-compatible"||f.clientType==="openai-compatible"}function NF(f){let $={region:f.region,apiLine:f.apiLine,openRouterProviderSorting:f.openRouterProviderSorting,modelCatalog:f.modelCatalog};if(MF(f))Object.assign($,{apiVersion:f.azure?.apiVersion,useIdentity:f.azure?.useIdentity});if(f.providerId==="bedrock")Object.assign($,{authentication:f.aws?.authentication,profile:f.aws?.profile,accessKeyId:f.aws?.accessKey,secretAccessKey:f.aws?.secretKey,sessionToken:f.aws?.sessionToken,usePromptCache:f.aws?.usePromptCache,useCrossRegionInference:f.useCrossRegionInference,useGlobalInference:f.useGlobalInference,endpoint:f.aws?.endpoint,customModelBaseId:f.aws?.customModelBaseId});if(f.providerId==="vertex"){let J=f.gcp?.region??f.region;Object.assign($,{project:f.gcp?.projectId,projectId:f.gcp?.projectId,location:J,region:J})}return zF($)}function KQ(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return OF[f.providerId]?.models??void 0}function qF(f){if(!f?.length)return;let $=new Set;for(let J of f)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":$.add(J);break;case"structured_output":$.add("structured-output");break;default:$.add("text")}return $.add("text"),[...$]}function yF(f,$){return{id:f,name:$.name??f,description:$.description,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxOutputTokens:$.maxTokens,capabilities:qF($.capabilities),metadata:{family:$.family,pricing:$.pricing,status:$.status,releaseDate:$.releaseDate}}}function ij(f,$,J){let Q=f.providerConfig,Z=Q?.providerId===f.providerId?Q:void 0,W={...Z??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Z?.apiKey,baseUrl:f.baseUrl??Z?.baseUrl,headers:f.headers??Z?.headers,knownModels:KQ(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};if(_F(TF(W.providerId)))return rj(()=>LF(W));return DF({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:NF(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,H])=>yF(j,H)):void 0}],logger:$,telemetry:J??f.telemetry??f.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as nj}from"@cline/shared";var wF=50000,CF=6000000,aj=8000,SF=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),EF=new Set(["read","read_files"]),u$="[outdated - see the latest file content]",tj="Tool execution was interrupted before a result was produced.",hF=(f)=>`
|
|
170
|
+
`).trim()}function c8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=$;return async(j,X,Y)=>{let V;try{V=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(V.protocol))throw Error(`Invalid protocol: ${V.protocol}. Only http and https are supported.`);let B=new AbortController,H=setTimeout(()=>B.abort(),f),A;if(Y.signal)A=()=>B.abort(),Y.signal.addEventListener("abort",A);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:W?"follow":"manual",signal:B.signal});if(clearTimeout(H),!W&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],F=0;while(!0){let{done:N,value:y}=await R.read();if(N)break;if(F+=y.length,F>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(y)}let D=new Uint8Array(F),_=0;for(let N of P)D.set(N,_),_+=N.length;let O=new TextDecoder("utf-8").decode(D),z;if(G.includes("text/html")||G.includes("application/xhtml"))z=ZD(O);else if(G.includes("application/json"))try{let N=JSON.parse(O);z=JSON.stringify(N,null,2)}catch{z=O}else z=O;let U=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${F} bytes`,"","--- Content ---",z.slice(0,50000)];if(z.length>50000)U.push(`
|
|
171
|
+
[Content truncated: showing first 50000 of ${z.length} characters]`);return U.push("","--- Analysis Request ---",`Prompt: ${X}`),U.join(`
|
|
172
|
+
`)}catch(K){if(clearTimeout(H),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function sf($={}){return{readFile:m8($.fileRead),search:v8($.search),bash:I8($.bash),webFetch:c8($.webFetch),applyPatch:x8($.applyPatch),editor:g8($.editor)}}var WD={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"},tf=[{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 FX($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((Q)=>J.includes(Q.toLowerCase()))}function jD($,f,J,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return FX(f,$.providerIdIncludes)&&FX(J,$.modelIdIncludes)}function of($,f,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!jD(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let W={};for(let[j,X]of Z.entries())W[WD[j]]=X;return W}var c0={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 b1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function HJ($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let Q of Q$)J[Q]=f;return J}function AJ($,f){let J=c0[$],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return j$({...W,...f})}import{createTool as HR,zodToJsonSchema as AR}from"@cline/shared";import{z as dQ}from"zod";import{createAgentRuntime as JR}from"@cline/agents";import{createContributionRegistry as QR}from"@cline/shared";import{createGateway as PD,createHandlerAsync as DD,hasRegisteredHandler as RD,MODEL_COLLECTIONS_BY_PROVIDER_ID as UD,normalizeProviderId as zD}from"@cline/llms";import{EMPTY_CONTENT_TEXT as XD}from"@cline/shared";function YD($){let f=BD($.content),J=[],Q=$.id??KD(),Z=0,W=[],j=()=>{if(W.length===0)return;let X=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:W.map(HD),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:PX($.metrics)}),W=[]};if(f.length===0)return J.push({id:Q,role:$.role,content:[{type:"text",text:XD}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:PX($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){W.push(X);continue}j(),J.push({id:`${Q}_tool_${X.tool_use_id}`,role:"tool",content:[RX(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function KJ($){return $.flatMap(YD)}function VD($){let f=$.content.map(UX).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:AD($.metrics)}}function ef($){return $.map(VD)}function GJ($){let f=[];for(let J of $){let Q=J.content.map(UX).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=f[f.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}f.push({role:Z,content:Q})}return f}function BD($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function HD($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return RX($)}}function RX($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function UX($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let f=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:f?.thoughtSignature??f?.signature}}case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function PX($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function AD($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var DX=0;function KD(){return DX+=1,`msg_${Date.now().toString(36)}_${DX.toString(36)}`}function GD($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:FD($),error:$.error}];default:return[]}}function FD($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function zX($){return{async*stream(f){let J=!1,Q=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let W=GJ(f.messages),j=f.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of Z.createMessage(f.systemPrompt??"",W,j))for(let Y of GD(X)){if(Y.type==="finish")J=!0;else if(Y.type==="tool-call-delta")Q=!0;yield Y}if(!J)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function LD($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function _D($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function OD($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(_D($))Object.assign(f,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return LD(f)}function SQ($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return UD[$.providerId]?.models??void 0}function MD($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function TD($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:MD(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function LX($,f,J){let Q=$.providerConfig,Z=Q?.providerId===$.providerId?Q:void 0,W={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:SQ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(RD(zD(W.providerId)))return zX(()=>DD(W));return PD({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:OD(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,X])=>TD(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{createMediaBudgetState as ND,IMAGE_OMITTED_PLACEHOLDER as _X,normalizeUserInput as OX,resolveMediaBudget as qD,validateAndReserveImageMedia as wD}from"@cline/shared";var yD=50000,SD=6000000,MX=8000,CD=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),ED=new Set(["read","read_files"]),u$="[outdated - see the latest file content]",TX="Tool execution was interrupted before a result was produced.",hD=($)=>`
|
|
165
173
|
|
|
166
|
-
...[truncated ${
|
|
174
|
+
...[truncated ${$} chars]...
|
|
167
175
|
|
|
168
|
-
`,
|
|
176
|
+
`,bD=($)=>`
|
|
169
177
|
|
|
170
|
-
...[truncated ${
|
|
178
|
+
...[truncated ${$} chars to fit provider request budget]...
|
|
171
179
|
|
|
172
|
-
`;class GQ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=wF,$=SF,J=CF){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=nj(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let H=this.transformBlock(j,Q.role);if(H!==j)Z=!0;return H});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let Z=nj(f.text);if(Z!==f.text)return{...f,text:Z};return f}if(f.type==="file"){let Z=this.truncateMiddle(f.content);return Z===f.content?f:{...f,content:Z}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),Q=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let Z=this.getReadLocators(f);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,f.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===f.content?f:{...f,content:Q}}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 Q=f[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let H=this.extractLocatorsFromReadToolInput(W.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(W.id,H)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let H=this.getReadLocators(W);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),W.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,W.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=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of f){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((Y)=>Y.type==="tool_result"),A=H.content.filter((Y)=>Y.type!=="tool_result");if(X.length>0){let Y=this.appendMissingToolResults({...H,role:"user",content:X},Q);if(j(Y),Q.size>0)Q.clear();Z=!0}if(A.length>0||X.length===0){if(X.length===0)W();let Y=X.length>0?{...H,content:A}:H;if(j(Y),Y.role==="assistant")this.trackMissingToolCalls(Y,$,Q)}continue}W(),j(H)}return W(),Z?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 Q of J.content)if(Q.type==="tool_result")$.add(Q.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 Q of f.content){if(Q.type!=="tool_use"||$.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${tj} Tool: ${f}.`:tj}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=[],Q=this.extractLocatorFromReadRequest($);if(Q)J.push(Q);if(Array.isArray($.files))for(let Z of $.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray($.file_paths)){for(let Z of $.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,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 Q of f){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}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((W)=>this.toReadLocatorKey(W))),Q=new Set($.map((W)=>W.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??u$;let Z=0;for(let W of f)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return f.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:u$}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:u$}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:u$};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!$.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(Q)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let Q={...f};if(typeof Q.result==="string")Q.result=u$;else if(typeof Q.content==="string")Q.content=u$;else Q.result=u$;return Q}isReadTool(f){return!!f&&EF.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 Q=this.truncateMiddle($.content);return Q===$.content?$:{...$,content:Q}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return PQ(f,this.maxToolResultChars,hF)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>IF(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if($<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=aj)continue;let j=$-this.maxTotalTextBytes,H=Math.max(aj,W-j),X=kF(Z.get(),H,bF);Z.set(X),$-=W-w0(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=w0(J.content);continue}for(let Q of J.content)if(Q.type==="text")$+=w0(Q.text);else if(Q.type==="thinking")$+=w0(Q.thinking);else if(Q.type==="file")$+=w0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")$+=w0(Q.content);else for(let Z of Q.content)if(Z.type==="text")$+=w0(Z.text);else if(Z.type==="file")$+=w0(Z.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){$.push({byteLength:w0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")$.push({byteLength:w0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")$.push({byteLength:w0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return $.sort((J,Q)=>Q.byteLength-J.byteLength)}}function w0(f){return Buffer.byteLength(f,"utf8")}function PQ(f,$,J){if(f.length<=$)return f;let Q=J(f.length-$),Z=Math.max(0,Math.floor(($-Q.length)/2)),W=Math.max(0,f.length-Z*2),j=J(W),H=Math.max(0,Math.floor(($-j.length)/2)),X=f.slice(0,H),A=H>0?f.slice(-H):"";return`${X}${j}${A}`}function kF(f,$,J){if(w0(f)<=$)return f;let Q=0,Z=f.length,W=PQ(f,0,J);while(Q<=Z){let j=Q+Z>>>1,H=PQ(f,j,J);if(w0(H)<=$)W=H,Q=j+1;else Z=j-1}return W}function IF(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function FQ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class UQ{messages=[];conversationId=FQ();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=FQ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=FQ(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function sj(f){let{agentConfig:$}=f,J=xF($),Q=mF($),Z=f.hooks,W=gF($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:Q,model:f.model,modelOptions:J,tools:f.tools,hooks:Z,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??$.telemetry,initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:W,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function xF(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 mF(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function gF(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function vF(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function cF(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function RQ(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(RQ);let $={};for(let J of Object.keys(f).sort())$[J]=RQ(f[J]);return $}function uF(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(RQ(f))}catch{return String(f)}}function dF(f,$,J,Q){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=Q.hardThreshold}}var oj={softThreshold:3,hardThreshold:5};class DQ{config;state=vF();constructor(f){this.config={softThreshold:f?.softThreshold??oj.softThreshold,hardThreshold:f?.hardThreshold??oj.hardThreshold}}inspect(f){let $=uF(f.input),J=dF(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(){cF(this.state)}}class LQ{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 Q=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(Q),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 Z=await pF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:lF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function lF(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 Q=f.stopReason?.trim();if(Q)$.push(`Decision: ${Q}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function pF(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 rF(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function iF(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 nF(f){return f.content.find(($)=>$.type==="tool-result")}function aF(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function tF(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 _Q{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=rF(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let Q=iF(f);if(Q!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:Q.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 Q=nF(f.message),Z=Q?.output,W=tF(Q);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,Q=f.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,H=(f.totalCost??0)-W;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:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,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:aF(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function ZU(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 WU(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function jU(f,$){let J=f.trim(),Q=$.map((Z)=>Z.trim()).filter(Boolean).join(`
|
|
180
|
+
`;class kQ{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=yD,f=CD,J=SD,Q={}){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J;this.mediaBudget=Q}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((Z)=>{if(!Array.isArray(Z.content)){if(Z.role==="user"&&typeof Z.content==="string"){let X=OX(Z.content);if(X!==Z.content)return{...Z,content:X}}return Z}let W=!1,j=Z.content.map((X)=>{let Y=this.transformBlock(X,Z.role);if(Y!==X)W=!0;return Y});return W?{...Z,content:j}:Z}),Q=this.applyMediaBudget(J);return this.truncateToTotalTextBudget(Q)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=OX($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),Q=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===$.content?$:{...$,content:Q}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let Q=$[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(W.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(W.id,X)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let X=this.getReadLocators(W);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),W.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,W.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(X)=>{let Y=J.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){J[J.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((B)=>B.type==="tool_result"),V=X.content.filter((B)=>B.type!=="tool_result");if(Y.length>0){let B=this.appendMissingToolResults({...X,role:"user",content:Y},Q);if(j(B),Q.size>0)Q.clear();Z=!0}if(V.length>0||Y.length===0){if(Y.length===0)W();let B=Y.length>0?{...X,content:V}:X;if(j(B),B.role==="assistant")this.trackMissingToolCalls(B,f,Q)}continue}W(),j(X)}return W(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")f.add(Q.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||f.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${TX} Tool: ${$}.`:TX}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],Q=this.extractLocatorFromReadRequest(f);if(Q)J.push(Q);if(Array.isArray(f.files))for(let Z of f.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let Q of $){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((W)=>this.toReadLocatorKey(W))),Q=new Set(f.map((W)=>W.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??u$;let Z=0;for(let W of $)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return $.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:u$}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:u$}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:u$};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(Q)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=u$;else if(typeof Q.content==="string")Q.content=u$;else Q.result=u$;return Q}isReadTool($){return!!$&&ED.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let J=this.truncateMiddle(f.content);return J===f.content?f:{...f,content:J}}if(f.type==="text"){let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}}if(u8(f))return this.truncateNestedStrings(f);return f})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let f=!1,J=$.map((Q)=>{let Z=this.truncateNestedStrings(Q);if(Z!==Q)f=!0;return Z});return f?J:$}if($!==null&&typeof $==="object"){if(FJ($))return $;let f=!1,J={};for(let[Q,Z]of Object.entries($)){let W=this.truncateNestedStrings(Z);if(W!==Z)f=!0;J[Q]=W}return f?J:$}return $}truncateMiddle($){return CQ($,this.maxToolResultChars,hD)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>ID(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if(f<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=MX)continue;let j=f-this.maxTotalTextBytes,X=Math.max(MX,W-j),Y=kD(Z.get(),X,bD);Z.set(Y),f-=W-F0(Y)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=F0(J.content);continue}for(let Q of J.content)if(Q.type==="text")f+=F0(Q.text);else if(Q.type==="thinking")f+=F0(Q.thinking);else if(Q.type==="file")f+=F0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")f+=F0(Q.content);else for(let Z of Q.content)if(Z.type==="text")f+=F0(Z.text);else if(Z.type==="file")f+=F0(Z.content);else if(u8(Z))f+=EQ(Z)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){f.push({byteLength:F0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")f.push({byteLength:F0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")f.push({byteLength:F0(W.content),get:()=>W.content,set:(j)=>{W.content=j}});else if(u8(W))hQ(W,f)}}return f.sort((J,Q)=>Q.byteLength-J.byteLength)}applyMediaBudget($){let f=this.resolveMediaBudget();if(f.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&f.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&f.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let J=ND(),Q=!1,Z=$.map((W)=>{if(!Array.isArray(W.content))return W;let j=!1,X=W.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,f,J);if(V!==Y)j=!0;return V});if(!j)return W;return Q=!0,{...W,content:X}});return Q?Z:$}resolveMediaBudget(){return qD(this.mediaBudget)}applyMediaBudgetToBlock($,f,J){if(FJ($))return this.limitImageContent($,f,J);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,Z=$.content.map((W)=>{let j=this.applyMediaBudgetToToolResultEntry(W,f,J);if(j!==W)Q=!0;return j});return Q?{...$,content:Z}:$}applyMediaBudgetToToolResultEntry($,f,J){if(FJ($))return this.limitImageContent($,f,J);if(u8($))return this.limitNestedMedia($,f,J);return $}limitNestedMedia($,f,J){if(FJ($)){let Q=this.limitImageContent($,f,J);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,Z=$.map((W)=>{let j=this.limitNestedMedia(W,f,J);if(j!==W)Q=!0;return j});return Q?Z:$}if($!==null&&typeof $==="object"){let Q=!1,Z={};for(let[W,j]of Object.entries($)){let X=this.limitNestedMedia(j,f,J);if(X!==j)Q=!0;Z[W]=X}return Q?Z:$}return $}limitImageContent($,f,J){if(!IQ($))return{type:"text",text:_X};let Q=wD($.mediaType,$.data,{maxImageEncodedBytes:f.maxImageEncodedBytes,maxImageDecodedBytes:f.maxImageDecodedBytes,maxTotalMediaBytes:f.maxTotalMediaBytes},J);if(!Q.ok)return{type:"text",text:_X};return{...$,data:Q.base64,mediaType:Q.mediaType}}}function F0($){return Buffer.byteLength($,"utf8")}function CQ($,f,J){if($.length<=f)return $;let Q=J($.length-f),Z=Math.max(0,Math.floor((f-Q.length)/2)),W=Math.max(0,$.length-Z*2),j=J(W),X=Math.max(0,Math.floor((f-j.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${j}${V}`}function kD($,f,J){if(F0($)<=f)return $;let Q=0,Z=$.length,W=CQ($,0,J);while(Q<=Z){let j=Q+Z>>>1,X=CQ($,j,J);if(F0(X)<=f)W=X,Q=j+1;else Z=j-1}return W}function ID($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>u8(f)?bQ(f):{...f})}}function u8($){if($===null||typeof $!=="object")return!1;let f=$.type;return f!=="text"&&f!=="image"&&f!=="file"}function FJ($){return $!==null&&typeof $==="object"&&$.type==="image"}function IQ($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function EQ($){if(typeof $==="string")return F0($);if(Array.isArray($)){let f=0;for(let J of $)f+=EQ(J);return f}if($!==null&&typeof $==="object"){if(IQ($))return 0;let f=0;for(let J of Object.values($))f+=EQ(J);return f}return 0}function hQ($,f){if(Array.isArray($)){$.forEach((J,Q)=>{if(typeof J==="string")f.push({byteLength:F0(J),get:()=>$[Q],set:(Z)=>{$[Q]=Z}});else hQ(J,f)});return}if($!==null&&typeof $==="object"){if(IQ($))return;let J=$;for(let Q of Object.keys(J)){let Z=J[Q];if(typeof Z==="string")f.push({byteLength:F0(Z),get:()=>J[Q],set:(W)=>{J[Q]=W}});else hQ(Z,f)}}}function bQ($){if(Array.isArray($))return $.map(bQ);if($!==null&&typeof $==="object"){let f={};for(let[J,Q]of Object.entries($))f[J]=bQ(Q);return f}return $}function xQ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class gQ{messages=[];conversationId=xQ();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=xQ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=xQ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function NX($){let{agentConfig:f}=$,J=xD(f),Q=gD(f),Z=$.hooks,W=mD(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:W,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function xD($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function gD($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function mD($){if($===void 0)return;return $>=2?"parallel":"sequential"}function vD(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function cD($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function mQ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(mQ);let f={};for(let J of Object.keys($).sort())f[J]=mQ($[J]);return f}function uD($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(mQ($))}catch{return String($)}}function dD($,f,J,Q){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var qX={softThreshold:3,hardThreshold:5};class vQ{config;state=vD();constructor($){this.config={softThreshold:$?.softThreshold??qX.softThreshold,hardThreshold:$?.hardThreshold??qX.hardThreshold}}inspect($){let f=uD($.input),J=dD(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){cD(this.state)}}class cQ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await pD({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:lD({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function lD($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let Q=$.stopReason?.trim();if(Q)f.push(`Decision: ${Q}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function pD($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function rD($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function iD($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function nD($){return $.content.find((f)=>f.type==="tool-result")}function aD($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function sD($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class uQ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=rD($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let Q=iD($);if(Q!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=nD($.message),Z=Q?.output,W=sD(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,X=($.totalCost??0)-W;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:aD($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function ZR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function WR($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function jR($,f){let J=$.trim(),Q=f.map((Z)=>Z.trim()).filter(Boolean).join(`
|
|
173
181
|
|
|
174
182
|
`);if(J&&Q)return`${J}
|
|
175
183
|
|
|
176
|
-
${Q}`;return J||Q}function HU(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let Q of $){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of $)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of $){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of $){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of $){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of $){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of $)await Q.onEvent?.(J)}}}class H${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 _Q;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??JU,this.conversation=new UQ(f.initialMessages),this.messageBuilder=new GQ,this.contributionRegistry=QU({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 LQ({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,H)=>XU(this.logger,W,j,H),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=f.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new DQ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of f)if(!$.has(Q.name))J.push(Q),$.add(Q.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 WU($);if(J)f.push(J)}return jU(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 YU(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Q=await this.composeSystemPrompt(),Z=ij(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of W)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let H=this.conversation.getConversationId(),X=fH(this.config),A=Array.from(j.values()),Y=Z6(this.conversation.getMessages()),V=sj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[Gj]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:Y,systemPrompt:Q}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),P,R;try{if(f.isContinue)P=await B.continue(void 0);else P=await B.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(P&&P.messages.length>0){let F=r1(P.messages);this.conversation.replaceMessages(F)}let G=new Date;try{return this.buildLegacyResult({runResult:P,thrownError:R,startedAt:$,endedAt:G})}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=HU([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let Q=J?.messages??$.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=r1(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:Z6(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(W6(f));return Z6($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)$=await Q.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,Q=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let Z=f.message.content.find((X)=>X.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?ZU(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(H),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${Q?`: ${Q}`:""}`})}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(r1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=r1($).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}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 Q=this.loopTracker.inspect({name:f,input:$});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${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:Q,endedAt:Z}=f,W=Z.getTime()-Q.getTime(),j=J?"error":AU($),H=$?.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=$?r1($.messages):this.conversation.getMessages(),Y=fH(this.config);if(J)throw J;return{text:H,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:Y},startedAt:Q,endedAt:Z,durationMs:W}}}function XU(f,$,J,Q){if(!f)return;if($==="debug"){f.debug(J,Q);return}if($==="error"&&f.error){f.error(J,Q);return}let Z=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...Q,severity:Z})}function AU(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function YU(f,$,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => ej);return Z(f,$,J,Q)}function fH(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=KQ(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as $H}from"@cline/shared";function JH(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return $H({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
|
|
177
|
-
${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function QH(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return $H({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function X$(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 d$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?JH(f.prompt,$):QH(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 A$(f){let $=d$(f),J=new H$($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var KU=OQ.object({systemPrompt:OQ.string().describe("System prompt defining the sub-agent's behavior"),task:OQ.string().describe("Task for the sub-agent to complete")});function Y$(f){return VU({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:BU(KU),execute:async($,J)=>{let Q=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],Z=A$({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:Q,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:H,input:$})}catch{}try{let X=await Z.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:W,conversationId:j,parentAgentId:H,input:$,result:A,agentResult:X})}catch{}return A}catch(X){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:H,input:$,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as W0,TEAM_AWAIT_TIMEOUT_MS as PU,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as GU,TEAM_RUN_TEXT_PREVIEW_LIMIT as FU,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as UU,TeamAttachOutcomeFragmentInputSchema as ZH,TeamAwaitRunsInputSchema as WH,TeamBroadcastInputSchema as jH,TeamBroadcastToolResultSchema as RU,TeamCancelRunInputSchema as HH,TeamCancelRunToolResultSchema as DU,TeamCleanupInputSchema as XH,TeamCleanupToolResultSchema as LU,TeamCreateOutcomeInputSchema as AH,TeamCreateOutcomeToolResultSchema as _U,TeamFinalizeOutcomeInputSchema as YH,TeamFinalizeOutcomeToolResultSchema as OU,TeamListOutcomesInputSchema as VH,TeamListRunsInputSchema as BH,TeamMailboxMessageToolResultSchema as TU,TeamMissionLogInputSchema as KH,TeamMissionLogToolResultSchema as zU,TeamOutcomeFragmentToolResultSchema as PH,TeamOutcomeToolResultSchema as MU,TeamReadMailboxInputSchema as GH,TeamReviewOutcomeFragmentInputSchema as FH,TeamRunTaskInputSchema as UH,TeamRunTaskToolResultSchema as TQ,TeamRunToolSummarySchema as zQ,TeamSendMessageInputSchema as RH,TeamSendMessageToolResultSchema as NU,TeamShutdownTeammateInputSchema as DH,TeamSimpleAgentStatusToolResultSchema as LH,TeamSpawnTeammateInputSchema as _H,TeamStatusInputSchema as OH,TeamStatusToolResultSchema as qU,TeamTaskInputSchema as TH,TeamTaskToolResultSchema as h8,validateWithZod as h,zodToJsonSchema as j0}from"@cline/shared";function zH(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function l$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function yU(f){let $=f.result;if(!$)return;return{textPreview:zH($.text,FU),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function j6(f){return f?.toISOString()}function MQ(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:zH(f.message,GU),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:j6(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:j6(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:j6(f.heartbeatAt),lastProgressAt:j6(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:yU(f)}}function wU(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 i1=["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 MH(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...p$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:d$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function n1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,Q=p$({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),Z=[];for(let W of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(W.agentId))continue;MH({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function p$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,Q=f.includeManagementTools??!0,Z=[];if(J)Z.push(W0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(_H),execute:async(j)=>{let H=h(_H,j);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:H.agentId,rolePrompt:H.rolePrompt};if(MH({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!Q)f.onLeadToolsUnlocked?.(p$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return h(LH,{agentId:H.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(W0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(DH),execute:async(j)=>{let H=h(DH,j);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(H.agentId,H.reason),h(LH,{agentId:H.agentId,status:"stopped"})}})),Z.push(W0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(OH),execute:async(j)=>{return h(OH,j),h(qU,f.runtime.getSnapshot())}})),Z.push(W0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(TH),execute:async(j)=>{let H=h(TH,j);switch(H.action){case"create":{let X=new Set(UU.create??[]),A=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),Y=f.runtime.createTask({title:l$(H.title,"title"),description:l$(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:f.requesterId});return h(h8,{action:"create",taskId:Y.id,status:Y.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return h(h8,{action:"list",tasks:f.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=f.runtime.claimTask(l$(H.taskId,"taskId"),f.requesterId);return h(h8,{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(l$(H.taskId,"taskId"),f.requesterId,l$(H.summary,"summary"));return h(h8,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(l$(H.taskId,"taskId"),f.requesterId,l$(H.reason,"reason"));return h(h8,{action:"block",taskId:X.id,status:X.status})}}}}));let W=new Map;return Z.push(W0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(UH),execute:async(j)=>{let H=h(UH,j);if(H.runMode==="async"){let Y=f.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0});return h(TQ,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${Y.id}.`,runId:Y.id})}let X=W.get(H.agentId);if(X){let Y=await X;return h(TQ,{...Y,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=f.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:f.requesterId,continueConversation:H.continueConversation||void 0}).then((Y)=>h(TQ,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:Y.text,iterations:Y.iterations})).finally(()=>{W.delete(H.agentId)});return W.set(H.agentId,A),await A}})),Z.push(W0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(HH),execute:async(j)=>{let H=h(HH,j),X=f.runtime.cancelRun(H.runId,H.reason);return h(DU,{runId:X.id,status:X.status})}})),Z.push(W0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(BH),execute:async(j)=>h(zQ.array(),f.runtime.listRuns(h(BH,j)).map(MQ))})),Z.push(W0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(WH),timeoutMs:PU,execute:async(j)=>{let H=h(WH,j);if(H.runId){let Y=await f.runtime.awaitRun(H.runId);return wU(Y),h(zQ,MQ(Y))}let X=await f.runtime.awaitAllRuns(),A=X.filter((Y)=>["failed","cancelled","interrupted"].includes(Y.status));if(A.length>0){let Y=A.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${Y}`)}return h(zQ.array(),X.map(MQ))}})),Z.push(W0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(RH),execute:async(j)=>{let H=h(RH,j),X=f.runtime.sendMessage(f.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return h(NU,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(W0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(jH),execute:async(j)=>{let H=h(jH,j),X=f.runtime.broadcast(f.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return h(RU,{delivered:X.length})}})),Z.push(W0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(GH),execute:async(j)=>{let H=h(GH,j);return h(TU.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(W0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(KH),execute:async(j)=>{let H=h(KH,j),X=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return h(zU,{id:X.id})}})),Z.push(W0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(XH),execute:async(j)=>{if(h(XH,j),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),h(LU,{status:"cleaned"})}})),Z.push(W0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(AH),execute:async(j)=>{let H=h(AH,j),X=f.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:f.requesterId});return h(_U,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(W0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(ZH),execute:async(j)=>{let H=h(ZH,j),X=f.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:f.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return h(PH,{fragmentId:X.id,status:X.status})}})),Z.push(W0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(FH),execute:async(j)=>{let H=h(FH,j),X=f.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:f.requesterId,approved:H.approved});return h(PH,{fragmentId:X.id,status:X.status})}})),Z.push(W0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(YH),execute:async(j)=>{let H=h(YH,j),X=f.runtime.finalizeOutcome(H.outcomeId);return h(OU,{outcomeId:X.id,status:X.status})}})),Z.push(W0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(VH),execute:async(j)=>{return h(VH,j),h(MU.array(),f.runtime.listOutcomes())}})),Z}function H6(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 NH(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var CU=[{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:Y$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...i1]}],SU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function EU(f){return f==="plan"||f==="yolo"?f:"act"}function yH(f){let $=EU(f.mode),J=g0[hf({mode:$})],Q=p1(f.providerId??"",f.modelId??"",$,l1);return{mode:$,flags:{...J,...Q,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function qH(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=yH($);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 Q=SU[f];return Q?J[Q]===!0:!1}function hU(f,$){if(f.id==="editor"){let{flags:J}=yH($),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:qH(f.id,$),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...f,defaultEnabled:qH(f.id,$)}}function r$(f={}){return CU.map(($)=>hU($,f))}function X6(f={}){return r$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function A6(f){if(!f.enabled)return new Set;let $=r$(f.availabilityContext),J=new Set($.map((Q)=>Q.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of f.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${$.map((Z)=>Z.id).join(", ")}`);return new Set(f.allowlist)}function b8(f,$={}){return r$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function Y6(f,$={}){return b8(f,$)}function i$(f={}){let{executorOptions:$={},executors:J,...Q}=f,Z={...d1($),...J??{}};return W$({...Q,executors:Z})}import{mkdirSync as gU,writeFileSync as vU}from"node:fs";import{dirname as cU}from"node:path";import{normalizeUserInput as uU}from"@cline/shared";import{nanoid as dU}from"nanoid";var CH={};q(CH,{sanitizeSessionToken:()=>n$,parseTeamTaskSubSessionId:()=>t1,parseSubSessionId:()=>I8,makeTeamTaskSubSessionId:()=>k8,makeSubSessionId:()=>a1,deriveSubsessionStatus:()=>x8});import{nanoid as IU}from"nanoid";function n$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function a1(f,$){let J=n$(f),Q=n$($),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function k8(f,$){let J=n$(f),Q=n$($);return`${J}__teamtask__${Q}__${IU(6)}`}function t1(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),H=Z.slice(W+2);if(!Q||!j||!H)return null;return{rootSessionId:Q,agentId:j,teamTaskId:H}}function I8(f){if(t1(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let Q=f.slice(0,J),Z=f.slice(J+$.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function x8(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as n}from"zod";var hH={};q(hH,{isTerminalSessionStatus:()=>EH,isNonTerminalSessionStatus:()=>J0,SessionSource:()=>F0,SESSION_STATUSES:()=>m8,NON_TERMINAL_SESSION_STATUSES:()=>SH});import{SESSION_STATUS_VALUES as xU}from"@cline/shared";var m8=xU,SH=["idle","running","pending"];function EH(f){return!SH.includes(f)}function J0(f){return!EH(f)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var mU=n.enum(m8),C0=n.object({version:n.literal(1),session_id:n.string().min(1),source:n.string().min(1),pid:n.number().int(),started_at:n.string().min(1),ended_at:n.string().min(1).optional(),exit_code:n.number().int().nullable().optional(),status:mU,interactive:n.boolean(),provider:n.string().min(1),model:n.string().min(1),cwd:n.string().min(1),workspace_root:n.string().min(1),team_name:n.string().min(1).optional(),enable_tools:n.boolean(),enable_spawn:n.boolean(),enable_teams:n.boolean(),prompt:n.string().optional(),metadata:n.record(n.string(),n.unknown()).optional(),messages_path:n.string().min(1).optional()});function bH(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function qQ(f,$){let J=[...f??[],...$??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function kH(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function bf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function NQ(f,$){let J={...f};J.id=bf(J.id)??dU();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:bf(Q?.id)??bf(J.modelId)??bf($?.id),provider:bf(Q?.provider)??bf(J.providerId)??bf($?.provider),family:bf(Q?.family)??bf($?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function V6(f){return f.map(($)=>NQ($))}function B6(f,$,J=[]){let Q=f.map((X,A)=>{let Y=J[A],B=Y?.role===X.role&&JSON.stringify(Y.content)===JSON.stringify(X.content)?{...Y,...X}:{...X};return NQ(B)}),Z=J.length,W=[];for(let X=Z;X<Q.length;X+=1)if(Q[X]?.role==="assistant")W.push(X);if(W.length===0){let X=[...Q].reverse().findIndex((A)=>A.role==="assistant");if(X===-1)return Q;W.push(Q.length-1-X)}let j=W[W.length-1],H=W.some((X)=>Q[X]?.metrics);for(let X of W){let A=Q[X],Y=A.metrics;if(!Y&&X===j&&!H){let V=$.usage;Y={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}Q[X]={...NQ(A,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...Y?{metrics:Y}:{},ts:A.ts??$.endedAt.getTime()}}return Q}function g8(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 lU=120;function a$(f){let $=f?.trim();return $?$.slice(0,lU):void 0}function yQ(f){let $=uU(f??"").trim();if(!$)return;return a$($.split(`
|
|
178
|
-
`)[0]?.trim())}function
|
|
179
|
-
`,"utf8")}function xH(f,$){return C0.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 mH(f,$,J){let Q=0;while(!0){let Z=await f();if(Z===void 0)return{updated:!1};let W=await $(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}_0();var gH={};q(gH,{summarizeUsageFromMessages:()=>o1,sumUsageTotals:()=>c8,getCurrentContextSize:()=>SQ,createInitialAccumulatedUsage:()=>K0,accumulateUsageTotals:()=>H0});function K0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0(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 c8(f){let $=K0();for(let J of f)$=H0($,J);return $}function s1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function o1(f){let $=K0();for(let J of f){let Q=J.metrics;if(!Q)continue;$=H0($,{inputTokens:s1(Q.inputTokens),outputTokens:s1(Q.outputTokens),cacheReadTokens:s1(Q.cacheReadTokens),cacheWriteTokens:s1(Q.cacheWriteTokens),totalCost:s1(Q.cost)})}return $}function SQ(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let Q=s1(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function pU(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function EQ(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 kf(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,Q=f.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:$,agentKind:Z,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:Q,teamAgentId:f.teamAgentId?.trim()||void 0}}function rU(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function iU(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 Q=J?.trim();if(Q)return Q}return f.isPrimaryAgentEvent?"root":"unknown"}function hQ(f,$,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=f,H=Z.telemetry,X=W?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,Y=EQ($),V=kf({agentId:J?.agentId??Y.agentId,conversationId:J?.conversationId??Y.conversationId,parentAgentId:J?.parentAgentId??Y.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 B=pU($.input);if(B)w4(H,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",K=!$.error;if(y4(H,{ulid:Q,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))C4(H,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:$.error,...V})}if($.type==="notice"&&$.reason==="api_error")e2(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.message,...V});if($.type==="error")e2(H,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:$.error?.message??"unknown error",...V});if($.type==="usage"&&W?.turnUsageBaseline){let B=rU($);if(A){W.turnPrimaryUsage=H0(W.turnPrimaryUsage??K0(),B);let P=H0(W.turnUsageBaseline,W.turnPrimaryUsage);f.usageBySession.set(Q,P),b1(H,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),N4(H,{ulid:Q,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:Z.modelId,...V})}else{let P=iU({isPrimaryAgentEvent:A,overrides:J,eventMetadata:Y}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(P,H0(R.get(P)??K0(),B))}let K=H0(W.turnPrimaryUsage??K0(),c8(W.turnUsageByAgent?.values()??[]));f.aggregateUsageBySession.set(Q,H0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if($.type==="iteration_end"&&A)f.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:kH($),ts:Date.now()}})}function B$(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as VL}from"@cline/shared";Af();import{existsSync as M6,readFileSync as dR,statSync as lR}from"node:fs";import{basename as pR,dirname as T6,join as N6,resolve as z6}from"node:path";import{discoverPluginModulePaths as rR,resolveConfiguredPluginModulePaths as GX,resolvePluginConfigSearchPaths as iR,SKILLS_CONFIG_DIRECTORY_NAME as nR}from"@cline/shared/storage";import{resolve as OR}from"node:path";import{normalizePluginManifest as TR}from"@cline/shared";import{existsSync as U0,readFileSync as $2}from"node:fs";import{builtinModules as QR,createRequire as mQ}from"node:module";import{dirname as K$,extname as p8,isAbsolute as ZR,resolve as l}from"node:path";import{fileURLToPath as tH}from"node:url";import{PLUGIN_FILE_EXTENSIONS as WR}from"@cline/shared";var sH=K$(tH(import.meta.url)),jR=mQ(import.meta.url),HR=l(sH,"..","..","..","..",".."),kQ=YR(HR),XR=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],gQ=new Set(QR.flatMap((f)=>[f,f.replace(/^node:/,"")])),l8=new Set(WR),AR=["development","node","import","require","default"];function YR(f){let $={},J={"@cline/sdk":l(f,"packages/sdk/src/index.ts"),"@cline/agents":l(f,"packages/agents/src/index.ts"),"@cline/core":l(f,"packages/core/src/index.ts"),"@cline/llms":l(f,"packages/llms/src/index.ts"),"@cline/shared":l(f,"packages/shared/src/index.ts"),"@cline/shared/storage":l(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":l(f,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(U0(Z))$[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=l(f,"packages",Q),W=l(Z,"package.json");if(!U0(W))continue;try{let j=JSON.parse($2(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=l(Z,j.exports);if(U0(H))$[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let A=VR(Z,X);if(!A)continue;let Y=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;$[Y]=A}}catch{}}return $}function VR(f,$){let J=vQ($);if(!J)return null;let Q=oH(f,J);for(let Z of Q)if(U0(Z))return Z;return null}function vQ(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 Q of AR){let Z=vQ(J[Q],$);if(Z)return Z}return null}function oH(f,$){let J=$.replace(/^\.\//,""),Q=[l(f,$)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[l(f,`${Z}.ts`),l(f,`${Z}.tsx`),l(f,`${Z}.mts`),l(f,`${Z}.cts`),...Q]}return Q}function BR(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function D6(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function f2(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function KR(f){let $=f2(f);if(f===$)return".";return`.${f.slice($.length)}`}function eH(f){return f2(f).startsWith("@cline/")}function IQ(f,$){let J=f2($),Q=K$(f);while(!0){let Z=l(Q,"node_modules",J);if(U0(Z)||U0(l(Z,"package.json")))return!0;let W=l(Q,"..");if(W===Q)return!1;Q=W}}function aH(f){return xQ(f)!==null}function xQ(f){try{return jR.resolve(f)}catch{}return PR(f)}function PR(f){let $=f2(f),J=fX($);if(!J)return null;let Q=l(J,"package.json");try{let Z=JSON.parse($2(Q,"utf8")),W=KR(f),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,H=vQ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=l(J,H),A=[X,...oH(J,H).filter((Y)=>Y!==X)];for(let Y of A)if(U0(Y))return Y;return null}catch{return null}}function GR(){let f=[sH],$=process.env.CLINE_WRAPPER_PATH?.trim();if($)f.push(K$(K$($)));let J=process.execPath?.trim();if(J)f.push(K$(J));return[...new Set(f.map((Q)=>l(Q)))]}function FR(f,$){let J=f;while(!0){let Q=l(J,"package.json");if(U0(Q))try{if(JSON.parse($2(Q,"utf8")).name===$)return J}catch{}let Z=l(J,"node_modules",$,"package.json");if(U0(Z))return K$(Z);let W=l(J,"..");if(W===J)return null;J=W}}function fX(f){for(let $ of GR()){let J=FR($,f);if(J)return J}return null}function UR(f){let J=K$(f);for(let Q=0;Q<4;Q++){let Z=l(J,"package.json");if(U0(Z))try{let j=JSON.parse($2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=l(J,"..");if(W===J)return!1;J=W}return!1}function $X(f,$){let J=$.startsWith("file:")?tH($):ZR($)?$:l(K$(f),$);if(U0(J)&&l8.has(p8(J)))return J;for(let Q of l8){let Z=`${J}${Q}`;if(U0(Z))return Z}for(let Q of l8){let Z=l(J,`index${Q}`);if(U0(Z))return Z}return null}function JX(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 Q of J)for(let Z of f.matchAll(Q)){let W=Z[1];if(W)$.add(W)}return[...$]}function RR(f){return p8(f)!==".ts"}function QX(f,$,J=new Set){if(J.has(f)||!U0(f))return;if(J.add(f),!l8.has(p8(f)))return;let Q=$2(f,"utf8"),Z=RR(f);for(let W of JX(Q)){if(W.startsWith("node:")||gQ.has(W))continue;if(D6(W)){if(!Z)continue;if(Object.hasOwn(kQ,W)||Object.hasOwn(kQ,f2(W))||IQ(f,W)||eH(W)&&aH(W)||$&&aH(W))continue;throw Error(`Cannot find module '${f2(W)}'`)}let j=$X(f,W);if(j)QX(j,$,J)}}function ZX(f,$=new Set,J=new Set){if($.has(f)||!U0(f))return J;if($.add(f),!l8.has(p8(f)))return J;let Q=$2(f,"utf8");for(let Z of JX(Q)){if(J.add(Z),D6(Z))continue;let W=$X(f,Z);if(W)ZX(W,$,J)}return J}function DR(f,$){let J=mQ(f),Q={},Z=ZX(f),W=new Set(XR);for(let[j,H]of Object.entries(kQ)){try{J.resolve(j);continue}catch{}Q[j]=H}for(let j of Z)if(D6(j)&&(eH(j)||$))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||IQ(f,j))continue;let H=xQ(j);if(H)Q[j]=H}if(!$)return Q;for(let j of Z){if(!D6(j)||Object.hasOwn(Q,j)||IQ(f,j)||j.startsWith("node:")||gQ.has(j))continue;let H=xQ(j);if(H)Q[j]=H}return Q}function LR(f){let $=p8(f);return $===".ts"||$===".tsx"||$===".mts"||$===".cts"}var s$;function _R(){if(s$!==void 0)return s$;let f=fX("jiti");if(!f)return s$=null,null;let $=l(f,"dist","babel.cjs");if(!U0($))return s$=null,null;try{let Q=mQ($)($);s$=typeof Q==="function"?Q:null}catch{s$=null}return s$}async function WX(f,$={}){let J=!UR(f);QX(f,J);let Q=DR(f,J),Z=BR(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let H=Object.entries(Z).filter(([,V])=>LR(V)).map(([V])=>V),X=_R(),A=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j(f,{alias:Z,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...gQ],transformModules:H,tryNative:!1,...A?{transform:A}:{}}).import(f,{})}function jX(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 HX(f){return typeof f==="object"&&f!==null}function cQ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function zR(f,$){if(!HX(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!cQ(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")&&!cQ(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!cQ(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function MR(f,$){if(!HX(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"`);zR(f,$)}async function r8(f,$={}){let J=OR($.cwd??process.cwd(),f),Q=await WX(J,{useCache:$.useCache}),Z=$.exportName??"plugin",W=Q.default??Q[Z];MR(W,J);let j=W,H=j.setup,X=H?(A,Y)=>{let V={...$.session,...Y.session},B={...Y,session:Object.keys(V).length>0?V:void 0,client:$.client??Y.client,user:$.user??Y.user,workspaceInfo:$.workspaceInfo??Y.workspaceInfo,automation:$.automation??Y.automation,logger:$.logger??Y.logger,telemetry:$.telemetry??Y.telemetry};return H(A,B)}:void 0;return{...j,manifest:TR(j.manifest),setup:X}}async function L6(f,$={}){return(await o$(f,$)).plugins}async function o$(f,$={}){let J=[],Q=[],Z=new Map,W=0;for(let H of f)try{let X=await r8(H,$);if(!jX(X.manifest,$))continue;let A=Z.get(X.name);if(A)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:A.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${A.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:W++})}catch(X){let A=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:A,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:Q}}import{existsSync as pQ}from"node:fs";import{createRequire as PX}from"node:module";import{dirname as _6,join as Q2}from"node:path";import{fileURLToPath as CR}from"node:url";var BX={};q(BX,{resolveSubprocessRuntimeExecutable:()=>uQ,buildSubprocessSandboxCommand:()=>VX,SubprocessSandbox:()=>J2,CLINE_JS_RUNTIME_PATH_ENV:()=>YX});import{spawn as NR}from"node:child_process";import{basename as qR}from"node:path";import{augmentNodeCommandForDebug as yR,withResolvedClineBuildEnv as wR}from"@cline/shared";function XX(f){if(f instanceof Error)return f;return Error(String(f))}var YX="CLINE_JS_RUNTIME_PATH";function AX(f){let $=f?.trim();if(!$)return!1;let J=qR($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function uQ(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[YX]?.trim();if(J)return J;let Q=f.execPath?.trim()||process.execPath;if(AX(Q))return Q;for(let Z of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let W=Z?.trim();if(W&&AX(W))return W}return"node"}function VX(f,$={}){let J=uQ({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return yR([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class J2{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??""],$=VX(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=NR($[0]??uQ(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:wR(process.env)});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${XX(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let H=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${H?`: ${H}`:""}`))})}async call(f,$,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:f,args:$};return await new Promise((j,H)=>{let X={resolve:(A)=>j(A),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(Z,X),Q.send(W,(A)=>{if(!A)return;let Y=this.clearPendingRequest(Z);if(!Y)return;Y.reject(Error(`${this.processLabel} failed to send call "${f}": ${XX(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 SR(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],rules:f.contributions?.rules??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function i8(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function ER(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function hR(){let f=process.env.CLINE_WRAPPER_PATH?.trim();if(!f)return;try{let J=PX(f).resolve(`${ER()}/package.json`),Q=Q2(_6(J),"extensions","plugin-sandbox-bootstrap.js");return pQ(Q)?Q:void 0}catch{return}}function bR(){let f=process.execPath?.trim();if(!f)return;let $=Q2(_6(_6(f)),"extensions","plugin-sandbox-bootstrap.js");return pQ($)?$:void 0}function kR(){let f=_6(CR(import.meta.url)),$=PX(import.meta.url),J=[Q2(f,"plugin-sandbox-bootstrap.js"),Q2(f,"extensions","plugin-sandbox-bootstrap.js"),Q2(f,"agents","plugin-sandbox-bootstrap.js"),hR(),bR()];for(let W of J.filter((j)=>typeof j==="string"))if(pQ(W))return{file:W};let Q=Q2(f,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
180
|
-
`)}}var
|
|
181
|
-
`).filter(Boolean);await Promise.allSettled(Z.map((W)
|
|
182
|
-
`),Q=[
|
|
183
|
-
`).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]
|
|
184
|
-
`,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??RD(OX(),"hooks.jsonl");OX(j),FD(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=oQ(Q,"");J({...R0(Z,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=qX(Q);J({...R0(Z,$),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:w6(Z.call.input)}});return},afterTool:async(Q)=>{let Z=yX(Q);J({...R0(Z,$),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:w6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:Q,result:Z})=>{let W=G$(Q);if(Z.status==="completed"){J({...R0(W,$),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||sQ(Z.error?.message)){J({...R0(W,$),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...R0(W,$),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=oQ({snapshot:Q.snapshot},wX(Q.message.content));J({...R0(Z,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function e8(f){let $=qD(f.workspacePath);if(!Object.values($).some((V)=>V.length>0))return;let Q=async(V,B)=>{let K=$[B]??[];if(K.length===0)return;J1({commands:K,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...R0(V,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...R0(V,f),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=$.prompt_submit??[];if(B.length>0)J1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},W=async(V)=>{let B=$.tool_call??[];if(B.length===0)return;return yD({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...R0(V,f),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:w6(V.call.input)}}})},j=async(V)=>{let B=$.tool_result??[];if(B.length===0)return;J1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:w6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=$.agent_end??[];if(B.length===0)return;J1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=$.agent_error??[];if(B.length===0)return;J1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},A=async(V)=>{if(sQ(V.reason)){let K=$.agent_abort??[];if(K.length>0)J1({commands:K,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;J1({commands:B,cwd:f.cwd,logger:f.logger,payload:{...R0(V,f),hookName:"session_shutdown",reason:V.reason}})},Y={};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)Y.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(G$(V.snapshot),B);return};if(($.prompt_submit?.length??0)>0)Y.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(oQ({snapshot:V.snapshot},wX(V.message.content)))}}if(($.tool_call?.length??0)>0)Y.beforeTool=async(V)=>{let B=await W(qX(V));return wD(B)};if(($.tool_result?.length??0)>0)Y.afterTool=async(V)=>{await j(yX(V));return};if(($.agent_end?.length??0)>0)Y.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...G$(V),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 V=Y.afterRun;Y.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:P}=B;if(P.status==="aborted"||sQ(P.error?.message)){await A({...G$(K),reason:P.error?.message});return}if(P.error)await X({...G$(K),iteration:P.iterations,error:P.error})}}return Y}function X2(f){return W2("core.hook_config_files",e8(f))}function Q1(f,$){let J=f.map((Q)=>Q[$]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function Z1(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:Q1($,"beforeRun"),afterRun:Q1($,"afterRun"),beforeModel:Q1($,"beforeModel"),afterModel:Q1($,"afterModel"),beforeTool:Q1($,"beforeTool"),afterTool:Q1($,"afterTool"),onEvent:Q1($,"onEvent")}}var CX={};q(CX,{normalizeRuntimeCapabilities:()=>D0});function D0(...f){let $,J;for(let Z of f){if(!Z)continue;if(Z.toolExecutors)$={...$??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=$&&Object.keys($).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var gX={};q(gX,{toProviderConfig:()=>c0,emptyStoredProviderSettings:()=>R$,StoredProviderSettingsSchema:()=>V2,StoredProviderSettingsEntrySchema:()=>o6,ProviderSettingsSchemaTyped:()=>WJ});import{z as U$}from"zod";var mX={};q(mX,{toProviderConfig:()=>c0,safeParseSettings:()=>s6,safeCreateProviderConfig:()=>AZ,parseSettings:()=>t6,normalizeProviderId:()=>Y2,isBuiltInProviderId:()=>HZ,createProviderConfig:()=>XZ,SapSettingsSchema:()=>i6,ReasoningSettingsSchema:()=>d6,ProviderSettingsSchema:()=>F$,ProviderProtocolSchema:()=>v6,ProviderIdSchema:()=>ZJ,ProviderClientSchema:()=>c6,OcaSettingsSchema:()=>n6,ModelCatalogSettingsSchema:()=>a6,GcpSettingsSchema:()=>p6,BUILT_IN_PROVIDER_IDS:()=>jZ,BUILT_IN_PROVIDER:()=>QJ,AzureSettingsSchema:()=>r6,AwsSettingsSchema:()=>l6,AuthSettingsSchema:()=>u6});import*as v0 from"@cline/llms";import{z as N}from"zod";var xX={};q(xX,{resolveProviderConfig:()=>JJ,getProviderConfig:()=>g6,getLiveModelsCatalog:()=>A2,clearPublicModelsCatalogCache:()=>tD,clearPrivateModelsCatalogCache:()=>WZ,clearLiveModelsCatalogCache:()=>ZZ,OPENAI_COMPATIBLE_PROVIDERS:()=>$J,DEFAULT_MODELS_CATALOG_URL:()=>k6});import*as X0 from"@cline/llms";function fZ(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter(($)=>$.length>0)}function CD(f,$){let J=fZ(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let Q=f,Z=fZ(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((H)=>H.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[$];if(W&&typeof W==="object"){let H=fZ(W.models??W);if(H.length>0)return H}return[]}async function C6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return CD(await J.json(),$)}function SX(f){return f.replace(/\/+$/,"")}function S6(f,$,J){let Q=J?.trim();if(!Q)return;let Z=f?.trim();if(!Z||!$?.trim())return Q;try{let W=new URL(Q),j=new URL($),H=new URL(Z);if(W.origin!==j.origin)return Q;let X=SX(j.pathname),A=SX(H.pathname);if(X&&W.pathname.startsWith(`${X}/`)){let Y=W.pathname.slice(X.length);H.pathname=`${A}${Y}`}else H.pathname=W.pathname;return H.search=W.search,H.hash=W.hash,H.toString()}catch{return Q}}function SD(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function ED(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 hD=Object.values(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:SD(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})),hX=Object.fromEntries(hD.map((f)=>[f.id,f]));function bD(f){return hX[f]}function kD(){return Object.fromEntries(Object.entries(hX).filter(([,f])=>ED(f)))}function bX(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 k6="https://models.dev/api.json",ID=600000,kX=300000,xD=5000,b6=new Map,fJ=new Map,$Z=new Map,E6=new Map;async function mD(){return X0.getGeneratedProviderModels()}async function gD(f,$={},J={},Q={},Z={},W={}){let j=await mD(),H=X0.resolveProviderModelCatalogKeys(f),X=Object.assign({},...H.map((V)=>j[V]??{})),A=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),Y=Object.keys(Z).length>0;if(A&&Y)return X0.sortModelsByReleaseDate({...Z,...W});if(f==="openai-codex")return X0.sortModelsByReleaseDate({...$,...X0.filterOpenAICodexModels(J),...Z,...W});return X0.sortModelsByReleaseDate({...X,...$,...J,...Q,...Z,...W})}function vD(f,$){let J=X0.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((Q)=>$[Q]??{}))}function I6(f){let $=f?.trim();return $&&$.length>0?$:""}function QZ(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function cD(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 uD(f,$){return`${f}:${I6($.baseUrl)}:${cD(QZ($)??"")}`}async function x6(f,$,J=xD){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch(f,{...$,signal:Q.signal})}finally{clearTimeout(Z)}}function W1(f,$,J){if(J&&!f.includes($))f.push($)}function m6(f,$){let J=["streaming","tools"];return W1(J,"images",Boolean($.supportsImages)),W1(J,"prompt-cache",Boolean($.supportsPromptCache)),W1(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxInputTokens:$.maxInputTokens,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function dD(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 Z=(await J.json())?.data??[],W={};for(let j of Z){let H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];W[H]=m6(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return W}function EX(f){if(typeof f==="number")return Number.isFinite(f)?f:void 0;if(typeof f==="string"){let $=Number(f);return Number.isFinite($)?$:void 0}return}async function lD(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 Z=(await J.json())?.data??[],W={};for(let j of Z){let H=j.id?.trim();if(!H)continue;W[H]=m6(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function pD(f,$){let Q=`${(I6(f.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await x6(Q,{method:"GET",headers:{Authorization:`Bearer ${$}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let A=X.id?.trim();if(!A)continue;let Y=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];W1(K,"tools",Y.includes("tools")),W1(K,"reasoning",Y.includes("reasoning")),W1(K,"temperature",V.includes("temperature")),W1(K,"images",B.includes("image"));let P={input:EX(X.pricing?.prompt),output:EX(X.pricing?.completion)};H[A]={id:A,name:X.name??A,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:P.input!==void 0||P.output!==void 0?P:void 0,status:"active"}}return H}function rD(f){let $=I6(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function iD(f,$){let Q=`${rD(f.baseUrl)}/v1/model/info`,Z=async(A)=>x6(Q,{method:"GET",headers:{accept:"application/json",...A}}),W=await Z({"x-litellm-api-key":$});if(!W.ok)W=await Z({Authorization:`Bearer ${$}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let H=(await W.json())?.data??[],X={};for(let A of H){let Y=A.model_name?.trim(),B=A.litellm_params?.model?.trim()||Y;if(!B)continue;let K=A.model_info,P=m6(B,{name:Y??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(X[B]=P,Y)X[Y]={...P,id:Y,name:Y}}return X}var IX={baseten:dD,hicap:lD,litellm:iD,poolside:pD},JZ=new Map,h6=new Map;function nD(f,$){return`${f}:${I6($.baseUrl)}`}async function aD(f,$,J){let Q=X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=S6(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=$?.cacheTtlMs??kX,j=nD(f,J),H=Date.now(),X=JZ.get(j);if(X&&X.expiresAt>H)return X.data;let A=h6.get(j);if(A)return A;let Y=C6(Z,f).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,m6(K,{name:K})]));return JZ.set(j,{data:B,expiresAt:H+W}),B}).finally(()=>{h6.delete(j)});return h6.set(j,Y),Y}function tD(){JZ.clear(),h6.clear()}async function sD(f,$){let J=QZ($);if(!J)return{};let Q=IX[f];if(!Q)return{};return Q($,J)}function oD(f,$,J){if(!J)return!1;if(!IX[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(QZ(J))}async function eD(f,$,J){let Q=$?.cacheTtlMs??kX,Z=uD(f,J),W=Date.now(),j=$Z.get(Z);if(j&&j.expiresAt>W)return j.data;let H=E6.get(Z);if(H)return H;let X=sD(f,J).then((A)=>{return $Z.set(Z,{data:A,expiresAt:W+Q}),A}).finally(()=>{E6.delete(Z)});return E6.set(Z,X),X}async function fL(f){return X0.fetchModelsDevProviderModels(f,globalThis.fetch)}async function A2(f={}){let $=f.url??k6,J=f.cacheTtlMs??ID,Q=Date.now(),Z=b6.get($);if(Z&&Z.expiresAt>Q)return Z.data;let W=fJ.get($);if(W)return W;let j=fL($).then((H)=>{return b6.set($,{data:H,expiresAt:Q+J}),H}).finally(()=>{fJ.delete($)});return fJ.set($,j),j}function ZZ(f){if(f){b6.delete(f),fJ.delete(f);return}b6.clear(),fJ.clear()}function WZ(){$Z.clear(),E6.clear()}function $L(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:bX(J.capabilities)}]))}var $J=$L(kD());function g6(f){let $=bD(f);if(!$)return;return{baseUrl:$.baseUrl||void 0,modelId:$.modelId,knownModels:$.knownModels,capabilities:bX($.capabilities)}}async function JJ(f,$,J){let Q=g6(f);if(!Q)return;try{let Z=$?.loadLatestOnInit?await A2($):void 0,W=Z?vD(f,Z):{},j=J&&oD(f,$,J)?await eD(f,$,J):{},X=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,A=X?await aD(f,$,X).catch(()=>({})):{},Y=await gD(f,Q.knownModels,W,j,A,J?.knownModels);return{...Q,knownModels:Y}}catch(Z){if($?.failOnError)throw Z;return Q}}var QJ=v0.BUILT_IN_PROVIDER,jZ=v0.BUILT_IN_PROVIDER_IDS,HZ=v0.isBuiltInProviderId,Y2=v0.normalizeProviderId,ZJ=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),v6=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),c6=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),u6=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),JL=N.enum(["none","low","medium","high","xhigh"]),d6=N.object({enabled:N.boolean().optional(),effort:JL.optional(),budgetTokens:N.number().int().positive().optional()}),l6=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),p6=N.object({projectId:N.string().optional(),region:N.string().optional()}),r6=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),i6=N.object({clientId:N.string().optional(),clientSecret:N.string().optional(),tokenUrl:N.string().url().optional(),resourceGroup:N.string().optional(),deploymentId:N.string().optional(),useOrchestrationMode:N.boolean().optional(),api:N.enum(["orchestration","foundation-models"]).optional(),defaultSettings:N.record(N.string(),N.unknown()).optional()}),n6=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),a6=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),F$=N.object({provider:ZJ,apiKey:N.string().optional(),auth:u6.optional(),model:N.string().optional(),protocol:v6.optional(),client:c6.optional(),routingProviderId:ZJ.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:d6.optional(),aws:l6.optional(),gcp:p6.optional(),azure:r6.optional(),sap:i6.optional(),oca:n6.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:a6.optional()});function t6(f){return F$.parse(f)}function s6(f){return F$.safeParse(f)}function QL(f){return f.protocol==="openai-responses"||f.client==="openai"}function c0(f,$={}){let J=f.provider,Q=Y2(J),Z=$.includeKnownModels!==!1,W=f.reasoning?.effort||"none",j=W==="none"?void 0:W,H=$J[Q],X=Object.assign({},...v0.resolveProviderModelCatalogKeys(Q).map((R)=>v0.getGeneratedModelsForProvider(R))),A=Object.keys(X)[0],Y=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,V=f.baseUrl??(Q==="oca"?f.oca?.mode==="internal"?l4:p4:H?.baseUrl),B=f.routingProviderId??(QL(f)&&Q!==QJ.OPENAI_NATIVE?QJ.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,P={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??H?.modelId??A??"default",...Z?{knownModels:K}:{},apiKey:Y,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:V,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxInputTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:j,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??H?.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(P).filter(([R,G])=>G!==void 0))}function XZ(f){let $=t6(f);return c0($)}function AZ(f){let $=s6(f);if($.success)return{success:!0,config:c0($.data)};return{success:!1,error:$.error}}var WJ=F$;var o6=U$.object({settings:F$,updatedAt:U$.string().datetime(),tokenSource:U$.enum(["manual","oauth","migration"]).default("manual")}),V2=U$.object({version:U$.literal(1),lastUsedProvider:U$.string().min(1).optional(),providers:U$.record(U$.string(),o6)});function R$(){return{version:1,providers:{}}}Af();var dX={};q(dX,{InMemoryWorkspaceManager:()=>K2});import{upsertWorkspaceInfo as HL,WorkspaceManifestSchema as VZ}from"@cline/shared";var uX={};q(uX,{normalizeWorkspacePath:()=>xf,generateWorkspaceInfoWithDiagnostics:()=>jJ,generateWorkspaceInfo:()=>B2,buildWorkspaceMetadataWithInfo:()=>YZ,buildWorkspaceMetadata:()=>HJ});import{basename as ZL,resolve as WL}from"node:path";import{performance as vX}from"node:perf_hooks";import{processWorkspaceInfo as cX}from"@cline/shared";import jL from"simple-git";function xf(f){return WL(f)}async function B2(f){return(await jJ(f)).info}function e6(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 jJ(f){let $=xf(f),J={rootPath:$,hint:ZL($)},Q;try{let Z=jL({baseDir:$});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=H}}catch(j){Q??=e6(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=e6(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=e6(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:e6(Z)}}}async function HJ(f){let $=await B2(f);return cX($)}async function YZ(f){let $=vX.now(),J=await jJ(f),Q=vX.now()-$,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:cX(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}class K2{manifest;listeners=new Set;constructor(f){this.manifest=VZ.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await B2(f);return this.manifest=HL(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=xf(f),J=this.manifest.workspaces[$];if(J)return this.manifest=VZ.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath($);return this.manifest=VZ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}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 $=xf(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}_0();import{createHash as XL}from"node:crypto";var lX=new Set,pX=new Set;function AL(f){return XL("sha256").update(f).digest("hex")}function YL(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function rX(f){if(!f.telemetry)return;let $=AL(f.rootPath),J=f.rootCount??1;if(!lX.has($))lX.add($),O4(f.telemetry,{root_count:J,vcs_types:YL(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!pX.has($)){pX.add($);let Q=Error(f.initError.message);Q.name=f.initError.errorType||"Error",T4(f.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function BL(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function KL(f,$,J){if($.length>0)for(let W of $)J?.log(W.message,{severity:"warn"});if(f.length===0)return;let Q=f.slice(0,3).map(BL).join("; "),Z=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of f)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function PL(f,$){let J=typeof f.thinking==="boolean",Q=typeof f.reasoningEffort==="string";if(!J&&!Q)return $;return{...$??{},...J?{enabled:f.thinking}:{},...Q?{effort:f.reasoningEffort}:{}}}function iX(f,$){return VL(f,$)}function GL(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 FL(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||UL(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 UL(f){let $=f?.trim();if(!$)return;let J=O0($),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function RL(f,$,J,Q,Z){let W=J.getProviderSettings(f.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,H=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0,X={...W??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.providerId==="openai-codex"?FL({sessionId:$,configHeaders:f.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:f.apiKey??W?.auth?.accessToken??W?.apiKey}):f.headers??W?.headers,reasoning:PL(f,W?.reasoning),modelCatalog:j},A={...c0(X),...H??{}};if(f.knownModels)A.knownModels=f.knownModels;if(f.extensionContext)A.extensionContext=f.extensionContext;let V=f.fetch??A.fetch??Z;if(V)A.fetch=V;return A}async function nX(f){let{input:$,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:A,createSubAgentLifecycleCallbacks:Y,createSpawnTool:V,localRuntime:B,readSessionMetadata:K,writeSessionMetadata:P}=f,R=B$($.config),{modelCatalogDefaults:G,userInstructionService:F,configExtensions:U,onTeamRestored:O,...M}=B??{},L=Object.keys(M).length>0?M:void 0,{workspaceInfo:D,workspaceMetadata:y,durationMs:b,vcsType:I,initError:o}=await YZ(R),Y0=L?.extensionContext,f0={...Y0??{},workspace:{...D,...Y0?.workspace??{}},session:{...Y0?.session??{},sessionId:J},logger:Y0?.logger??L?.logger,telemetry:Y0?.telemetry??L?.telemetry??Z};rX({telemetry:f0.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:I,durationMs:b,initError:o,featureFlagEnabled:!0});let t=X2({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:L?.logger,workspaceInfo:D}),o0=bH(L?.hooks)?void 0:H2({rootSessionId:J,workspacePath:R,workspaceInfo:D}),E$=Z1([L?.hooks,o0]),i;if(iX(U,"plugins"))try{i=await Z2({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:X,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:D,session:f0.session,client:f0.client,user:f0.user,logger:f0.logger,telemetry:f0.telemetry,automation:f0.automation}),KL(i.failures,i.warnings,L?.logger)}catch(h1){let w9=h1 instanceof Error?h1.message:String(h1);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${w9})`)}let w=qQ(t?[t]:void 0,qQ(L?.extensions,R6(i?.extensions))),G0=iX(U,"plugins")?f1(i?.pluginPaths??[]):void 0,Q0={...$.config,...L??{},sessionId:J,hooks:E$,extensions:w,extensionContext:f0,telemetry:f0.telemetry},y0=RL(Q0,J,Q,G,H),S1=Z1([Q0.hooks,Q0.checkpoint?.enabled===!0?_X({cwd:Q0.cwd,sessionId:J,logger:Q0.logger,createCheckpoint:Q0.checkpoint?.createCheckpoint,initialRunCount:GL($.initialMessages),readSessionMetadata:K,writeSessionMetadata:P}):void 0]),Of={...Q0,providerConfig:y0,workspaceMetadata:y,hooks:S1},Wf=$.toolPolicies??Q0.toolPolicies??j,s2=D0(W,$.capabilities),E1=s2?.requestToolApproval,R4=s2?.toolExecutors,Tf=Y?.(Of),D4=new K2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:$,config:Of,providerConfig:y0,workspaceMetadata:y,workspaceInfo:D,extensions:w,hooks:S1,toolPolicies:Wf,requestToolApproval:E1,pluginSandboxShutdown:i?.shutdown,runtimeBuilderInput:{config:Of,hooks:S1,extensions:w,onTeamEvent:A,createSpawnTool:V,onTeamRestored:O,onSubAgentEvent:Tf?.onSubAgentEvent,onSubAgentStart:Tf?.onSubAgentStart,onSubAgentEnd:Tf?.onSubAgentEnd,userInstructionService:F,pluginSkillDirectories:G0,configExtensions:U,toolExecutors:R4,toolPolicies:Wf,workspaceManager:D4,logger:Of.logger,telemetry:Of.telemetry,requestToolApproval:E1}}}import{existsSync as $5,mkdirSync as DL,readdirSync as LL,rmdirSync as _L,rmSync as OL,unlinkSync as TL}from"node:fs";import{dirname as aX,join as f5}from"node:path";function s(){return new Date().toISOString()}function XJ(f){if(!f||!$5(f))return;try{TL(f)}catch{}}function zL(f){let $=t1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=I8(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class BZ{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return f5(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!$5($))DL($,{recursive:!0});return $}sessionMessagesPath(f){return f5(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return f5(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!$5($)){$=aX($);continue}try{if(LL($).length>0)break;_L($)}catch{break}$=aX($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!$5(f))return;try{OL(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:Q,fileStem:Z}=zL(f),W=this.sessionArtifactsDir(Q);return{messagesPath:f5(W,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as ML}from"@cline/shared/storage";_0();function tX(f,$,J,Q,Z){if(J)M4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});else z4(f.telemetry,{ulid:$,apiProvider:f.providerId,...Z});NL(f.telemetry,{workspacePath:Q})}function NL(f,$){let J=ML("Hooks"),Q=P$($.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[W,j]of Z.entries())k4(f,W,j.global,j.workspace)}function sX(f,$){for(let J of $.mentions)h4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)S4(f,"file",J.length);for(let J of $.ignoredMentions)E4(f,"file","not_found",J)}var gK={};q(gK,{ProviderSettingsManager:()=>Lf});import{chmodSync as cK,existsSync as r7,mkdirSync as WS,readFileSync as jS,writeFileSync as HS}from"node:fs";import{basename as uK,dirname as i7}from"node:path";import{resolveProviderSettingsPath as XS}from"@cline/shared/storage";var T={};q(T,{writeHubDiscovery:()=>w5,writeGlobalSettings:()=>If,withHubStartupLock:()=>C5,verifyHubConnection:()=>Kf,updateMcpServerOAuthState:()=>Y1,updateLocalProvider:()=>G9,uninstallPlugin:()=>R7,truncateNotificationBody:()=>H4,toggleDisabledTool:()=>F6,toTeamProgressLifecycleEvent:()=>S2,toProviderConfig:()=>c0,toHubHealthUrl:()=>oZ,toHookConfigFileName:()=>o8,summarizeUsageFromMessages:()=>o1,stopLocalHubServerGracefully:()=>YW,startLocalOAuthServer:()=>e0,startHubWebSocketServer:()=>q1,startHubServer:()=>mB,startClineDeviceAuth:()=>x9,splitCoreSessionConfig:()=>CJ,spawnDetachedHubServerWithRetry:()=>z2,spawnDetachedHubServer:()=>ZW,setTelemetryOptOutGlobally:()=>uH,setMcpServerDisabled:()=>X1,setDisabledTools:()=>bQ,setDisabledPlugin:()=>nH,setAutoUpdateEnabledGlobally:()=>lH,sendHubCommand:()=>uV,saveProviderOAuthCredentials:()=>I$,saveLocalProviderSettings:()=>N7,saveLocalProviderOAuthCredentials:()=>C7,sanitizeSessionToken:()=>n$,safeParseSettings:()=>s6,safeCreateProviderConfig:()=>AZ,runSubprocessEvent:()=>k2,runHook:()=>x2,reviveTeamStateDates:()=>H6,restartLocalHubIfIdleAfterStartupTimeout:()=>h5,resolveWorkspaceHubOwnerContext:()=>kY,resolveWorkflowsConfigSearchPaths:()=>DJ,resolveSkillsConfigSearchPaths:()=>UJ,resolveSharedHubOwnerContext:()=>A0,resolveSessionBackend:()=>CW,resolveRulesConfigSearchPaths:()=>RJ,resolveProviderConfig:()=>JJ,resolveProviderApiKeyFromSettings:()=>d9,resolvePluginSkillDirectoriesFromPaths:()=>f1,resolvePluginConfigSearchPaths:()=>n8,resolveMcpServerRegistrations:()=>Yf,resolveLocalClineAuthToken:()=>E7,resolveHubUrl:()=>kW,resolveHubOwnerContext:()=>uf,resolveHubEndpointOptions:()=>r0,resolveHubBuildId:()=>z$,resolveHooksConfigSearchPaths:()=>t8,resolveDisabledToolNames:()=>Xf,resolveDisabledPluginPaths:()=>d8,resolveDefaultMcpSettingsPath:()=>z0,resolveDefaultHubPort:()=>T2,resolveDefaultHubPathname:()=>QW,resolveDefaultHubHost:()=>JW,resolveCoreSelectedToolIds:()=>A6,resolveCompatibleLocalHubUrl:()=>rJ,resolveClineDir:()=>SY,resolveClineDataDir:()=>uJ,resolveAndLoadAgentPlugins:()=>Z2,resolveAgentPluginPaths:()=>e$,requestHubShutdown:()=>pJ,requestDesktopToolApproval:()=>Y7,rememberRecoverableLocalHubUrl:()=>M$,registerRemoteConfigSessionBlobUpload:()=>Q9,registerMcpServersFromSettingsFile:()=>V1,registerDisposable:()=>$S,refreshProviderModelsFromSource:()=>q7,refreshOpenAICodexToken:()=>d4,refreshOcaToken:()=>i4,refreshClineToken:()=>c4,readSessionCheckpointHistory:()=>X4,readRemoteConfigSessionBlobUploadMetadata:()=>$7,readHubDiscovery:()=>P0,readGlobalSettings:()=>T0,probeHubServer:()=>Bf,probeHubConnection:()=>cV,prewarmFileIndex:()=>f6,prewarmDetachedHubServer:()=>S5,prepareRemoteConfigCoreIntegration:()=>Q7,parseWorkflowConfigFromMarkdown:()=>FJ,parseUserCommandEnvelope:()=>fS,parseSkillConfigFromMarkdown:()=>PJ,parseSettings:()=>t6,parseRuleConfigFromMarkdown:()=>GJ,parseHookEventPayload:()=>I2,parseConfiguredAgentConfig:()=>tJ,normalizeWorkspacePath:()=>xf,normalizeUserInput:()=>eC,normalizeSdkError:()=>oC,normalizeRuntimeCapabilities:()=>D0,normalizeProviderId:()=>Y2,normalizeOAuthProvider:()=>y7,normalizeHubWebSocketUrl:()=>N$,noopBasicLogger:()=>sC,migrateLegacyProviderSettings:()=>G4,mergeRulesForSystemPrompt:()=>R2,mergeAgentHooks:()=>Z1,makeTeamTaskSubSessionId:()=>k8,makeSubSessionId:()=>a1,loginOpenAICodex:()=>Q8,loginOcaOAuth:()=>j8,loginLocalProvider:()=>w7,loginClineOAuth:()=>$8,loginAndSaveProviderOAuthCredentials:()=>X8,loginAndSaveLocalProviderOAuthCredentials:()=>S7,loadOpenTelemetryAdapter:()=>gC,loadMcpSettingsFile:()=>H1,loadLlmsConfigFromFile:()=>d7,loadConfiguredAgentConfigs:()=>y2,loadAgentPluginsFromPathsWithDiagnostics:()=>o$,loadAgentPluginsFromPaths:()=>L6,loadAgentPluginFromPath:()=>r8,listSessionHistoryFromBackend:()=>nZ,listPluginToolsWithDiagnostics:()=>L5,listPluginTools:()=>yJ,listMcpServerOAuthStatuses:()=>NJ,listLocalProviders:()=>z7,listHookConfigFiles:()=>P$,isToolDisabledGlobally:()=>pH,isTelemetryOptedOutGlobally:()=>G6,isSessionNotFoundError:()=>cf,isRuleEnabled:()=>V5,isPluginDisabledGlobally:()=>iH,isOAuthProvider:()=>k$,isHubReconnectableTransportError:()=>XW,isHubCommandTimeoutError:()=>E5,isDiscoveryFilePresent:()=>hY,isClineAccountActionRequest:()=>J5,isBuiltInProviderId:()=>HZ,isAutoUpdateEnabledGlobally:()=>dH,identifyAccount:()=>yf,hasMcpSettingsFile:()=>gf,getValidOpenAICodexCredentials:()=>Z8,getValidOcaCredentials:()=>H8,getValidClineCredentials:()=>J8,getProviderOAuthCredentialsFromSettings:()=>A8,getProviderConfigFields:()=>h7,getProviderConfig:()=>g6,getProviderAuthStorageId:()=>u9,getProviderAuthHandler:()=>V0,getPersistedProviderApiKey:()=>a4,getMcpServerOAuthState:()=>A1,getLocalProviderModels:()=>M7,getLiveModelsCatalog:()=>A2,getFileIndex:()=>Ef,getCurrentContextSize:()=>SQ,getCoreHeadlessToolNames:()=>b8,getCoreDefaultEnabledToolIds:()=>X6,getCoreBuiltinToolCatalog:()=>r$,getCoreAcpToolNames:()=>Y6,getClineDefaultSystemPrompt:()=>cC,generateWorkspaceInfoWithDiagnostics:()=>jJ,generateWorkspaceInfo:()=>B2,formatRulesForSystemPrompt:()=>U2,formatProviderOAuthApiKey:()=>l9,formatDisplayUserInput:()=>tC,filterExtensionToolRegistrations:()=>R6,filterDisabledTools:()=>t$,filterDisabledPluginPaths:()=>U6,fetchClineRecommendedModels:()=>c7,executeClineAccountAction:()=>Q5,ensureHubWebSocketServer:()=>e5,ensureHubServer:()=>gB,ensureDetachedHubServer:()=>xY,ensureCustomProvidersLoaded:()=>B9,ensureCompatibleLocalHubUrl:()=>D1,enrichPromptWithMentions:()=>u1,emptyWorkspaceManifest:()=>aC,emptyStoredProviderSettings:()=>R$,discoverPluginModulePaths:()=>a8,deriveSubsessionStatus:()=>x8,deleteLocalProvider:()=>F9,defineLlmsConfig:()=>u7,createWorkflowsConfigDefinition:()=>OJ,createUserInstructionConfigService:()=>D$,createToolPoliciesWithPreset:()=>J6,createTool:()=>nC,createTeamName:()=>j9,createSubprocessHooks:()=>d5,createSpawnAgentTool:()=>Y$,createSkillsConfigDefinition:()=>LJ,createSessionHost:()=>b2,createRuntimeHost:()=>b2,createRulesConfigDefinition:()=>_J,createRemoteConfigSessionMessagesArtifactUploader:()=>J7,createProviderConfig:()=>XZ,createOpenTelemetryTelemetryService:()=>j4,createOAuthClientCallbacks:()=>P2,createMcpTools:()=>_2,createLocalHubScheduleRuntimeHandlers:()=>f9,createLlmsSdk:()=>p7,createInitialAccumulatedUsage:()=>K0,createInMemoryHubOwnerContext:()=>EY,createHubServerUrl:()=>Jf,createHubAuthToken:()=>y5,createHookConfigFileHooks:()=>e8,createHookConfigFileExtension:()=>X2,createHookAuditHooks:()=>H2,createDisabledMcpToolPolicy:()=>qJ,createDisabledMcpToolPolicies:()=>D5,createDelegatedAgentConfigProvider:()=>X$,createDelegatedAgent:()=>A$,createDefaultToolsWithPreset:()=>Q6,createDefaultTools:()=>W$,createDefaultMcpServerClientFactory:()=>L2,createDefaultExecutors:()=>d1,createCoreSettingsService:()=>K1,createCoreSessionSnapshot:()=>Pf,createContributionRegistry:()=>iC,createContextCompactionPrepareTurn:()=>G8,createConfiguredTelemetryService:()=>nf,createConfiguredTelemetryHandle:()=>u2,createConfiguredAgentTools:()=>w2,createClineTelemetryServiceMetadata:()=>rC,createClineTelemetryServiceConfig:()=>pC,createBuiltinTools:()=>i$,createAgentTeamsTools:()=>p$,createAgentRuntime:()=>ZS,createAgentHooksExtension:()=>W2,connectToHub:()=>i5,completeClineDeviceAuth:()=>m9,clearPrivateModelsCatalogCache:()=>WZ,clearLiveModelsCatalogCache:()=>ZZ,clearHubDiscovery:()=>p0,captureWorkspacePathResolved:()=>V3,captureWorkspaceInitialized:()=>O4,captureWorkspaceInitError:()=>T4,captureToolUsage:()=>y4,captureTokenUsage:()=>N4,captureTaskRestarted:()=>M4,captureTaskCreated:()=>z4,captureTaskCompleted:()=>o2,captureSubagentExecution:()=>f8,captureSkillUsed:()=>w4,captureSdkError:()=>lC,captureProviderConfigured:()=>B3,captureProviderApiError:()=>e2,captureModeSwitch:()=>q4,captureMentionUsed:()=>S4,captureMentionSearchResults:()=>h4,captureMentionFailed:()=>E4,captureHookDiscovery:()=>k4,captureExtensionActivated:()=>Y3,captureDiffEditFailure:()=>C4,captureConversationTurnEvent:()=>b1,captureCompactionSkipped:()=>x4,captureCompactionExecuted:()=>I4,captureAuthSucceeded:()=>Nf,captureAuthStarted:()=>Mf,captureAuthLoggedOut:()=>sf,captureAuthFailed:()=>qf,captureAgentTeamCreated:()=>b4,captureAgentCreated:()=>of,buildWorkspaceMetadata:()=>HJ,buildTeamProgressSummary:()=>C2,buildSdkErrorProperties:()=>uC,buildRemoteConfigSessionBlobUploadMetadata:()=>$9,buildDelegatedAgentConfig:()=>d$,buildConfiguredAgentToolName:()=>sJ,buildConfiguredAgentToolDescriptors:()=>oJ,bootstrapAgentTeams:()=>n1,authorizeMcpServerOAuth:()=>F5,addLocalProvider:()=>T7,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>KJ,UnifiedConfigFileWatcher:()=>j1,ToolPresets:()=>g0,TelemetryService:()=>v2,TelemetryLoggerSink:()=>W4,TEAM_TOOL_NAMES:()=>i1,SubprocessSandbox:()=>J2,StoredProviderSettingsSchema:()=>V2,StoredProviderSettingsEntrySchema:()=>o6,SqliteTeamStore:()=>y1,SqliteSessionStore:()=>Ff,SessionVersioningService:()=>C$,SessionVersioningError:()=>h0,SessionSource:()=>F0,SessionNotFoundError:()=>vf,SapSettingsSchema:()=>i6,SKILLS_CONFIG_DIRECTORY_NAME:()=>BJ,SESSION_STATUSES:()=>m8,SESSION_NOT_FOUND_ERROR_CODE:()=>P1,SDK_ERROR_TELEMETRY_EVENT:()=>JS,RpcClineAccountService:()=>YJ,RemoteRuntimeHost:()=>q2,ReasoningSettingsSchema:()=>d6,RULES_CONFIG_DIRECTORY_NAME:()=>Y5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>J9,ProviderSettingsSchema:()=>F$,ProviderSettingsManager:()=>Lf,ProviderProtocolSchema:()=>v6,ProviderIdSchema:()=>ZJ,ProviderClientSchema:()=>c6,OpenTelemetryProvider:()=>c2,OcaSettingsSchema:()=>n6,OPENAI_COMPATIBLE_PROVIDERS:()=>$J,NodeHubClient:()=>Qf,NativeHubTransportAdapter:()=>B4,ModelCatalogSettingsSchema:()=>a6,LocalRuntimeHost:()=>Df,Llms:()=>vC,InMemoryWorkspaceManager:()=>K2,InMemoryMcpManager:()=>B1,HubUIClient:()=>mW,HubTransportError:()=>M0,HubSessionClient:()=>xW,HubServerTransport:()=>l2,HubScheduleService:()=>g2,HubScheduleCommandService:()=>m2,HubRuntimeHost:()=>df,HubCommandError:()=>M2,HookEventPayloadSchema:()=>u5,HookEventNameSchema:()=>c5,HookConfigFileName:()=>j2,HOOK_CONFIG_FILE_EVENT_MAP:()=>s8,HOOKS_CONFIG_DIRECTORY_NAME:()=>q6,GlobalSettingsSchema:()=>u8,GcpSettingsSchema:()=>p6,FileTeamPersistenceStore:()=>L9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>N9,DefaultToolNames:()=>B0,DefaultRuntimeBuilder:()=>i2,DefaultLlmsSdk:()=>F4,DEFAULT_MODELS_CATALOG_URL:()=>k6,DEFAULT_HUB_PORT:()=>fW,DEFAULT_HUB_PATHNAME:()=>$W,DEFAULT_HUB_HOST:()=>eZ,CoreSettingsService:()=>L$,CoreSessionService:()=>Rf,ContributionRegistry:()=>dC,ClineCore:()=>Q4,ClineAccountService:()=>AJ,ChatViewStateSchema:()=>g7,ChatSummarySchema:()=>M9,ChatSessionStatusSchema:()=>O9,ChatSessionConfigSchema:()=>_9,ChatMessageSchema:()=>z9,ChatMessageRoleSchema:()=>T9,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>v7,BrowserWebSocketHubAdapter:()=>V4,BUILT_IN_PROVIDER_IDS:()=>jZ,BUILT_IN_PROVIDER:()=>QJ,AzureSettingsSchema:()=>r6,AwsSettingsSchema:()=>l6,AuthSettingsSchema:()=>u6,AgentTeamsRuntime:()=>O1,AgentTeam:()=>h2,Agent:()=>QS,ALL_DEFAULT_TOOL_NAMES:()=>J$});z(T,tp);import*as vC from"@cline/llms";import{buildClineSystemPrompt as cC,buildSdkErrorProperties as uC,ContributionRegistry as dC,captureSdkError as lC,createClineTelemetryServiceConfig as pC,createClineTelemetryServiceMetadata as rC,createContributionRegistry as iC,createTool as nC,emptyWorkspaceManifest as aC,formatDisplayUserInput as tC,noopBasicLogger as sC,normalizeSdkError as oC,normalizeUserInput as eC,parseUserCommandEnvelope as fS,registerDisposable as $S,SDK_ERROR_TELEMETRY_EVENT as JS}from"@cline/shared";import"@cline/shared/storage";var eX={};q(eX,{isClineAccountActionRequest:()=>J5,executeClineAccountAction:()=>Q5,RpcClineAccountService:()=>YJ,ClineAccountService:()=>AJ});function qL(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function oX(f,$,J){let Q=qL(J);if(Q)return Q;let Z=$.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${f}: ${W}`}return`Cline account request failed with status ${f}`}class AJ{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 Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===f)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return j}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:Z.signal});if(j.status===204||$?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(oX(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(oX(j.status,H,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(W)}}}function J5(f){return f.action==="clineAccount"}async function Q5(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 YJ{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}var fA={};q(fA,{createOAuthClientCallbacks:()=>P2});function P2(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((Q)=>{f.onOpenUrlError?.({url:$,error:Q})})}catch(Q){f.onOpenUrlError?.({url:$,error:Q})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}var hV={};q(hV,{ClineCore:()=>Q4});function $A(f){if(f===!0)return{};if(!f)return;return f}function JA(f){if(f==="user")return"global";return f}class KZ{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 QA(f){let{host:$}=f;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Y2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:CL(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:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await $.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:wL(Z)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function Z5(f){let $=yL(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),Q=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),Z=f.context?.logger??f.logger,W=f.context?.telemetry??f.telemetry;if(!$&&!J&&!Q&&!Z&&!W)return f.context;return{...f.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...$?{automation:$}:{}}}function yL(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function wL(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 CL(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var pA={};q(pA,{createCoreSettingsService:()=>K1,CoreSettingsService:()=>L$});import{existsSync as _5}from"node:fs";import{basename as uA,isAbsolute as s_,relative as o_}from"node:path";var RA={};q(RA,{resolveWorkflowsConfigSearchPaths:()=>DJ,resolveSkillsConfigSearchPaths:()=>UJ,resolveRulesConfigSearchPaths:()=>RJ,parseWorkflowConfigFromMarkdown:()=>FJ,parseSkillConfigFromMarkdown:()=>PJ,parseRuleConfigFromMarkdown:()=>GJ,createWorkflowsConfigDefinition:()=>OJ,createUserInstructionConfigService:()=>D$,createSkillsConfigDefinition:()=>LJ,createRulesConfigDefinition:()=>_J,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>KJ,UnifiedConfigFileWatcher:()=>j1,SKILLS_CONFIG_DIRECTORY_NAME:()=>BJ,RULES_CONFIG_DIRECTORY_NAME:()=>Y5});import{createHash as SL}from"node:crypto";import{watch as EL}from"node:fs";import{readdir as hL,readFile as bL}from"node:fs/promises";import{join as kL}from"node:path";function IL(f){return SL("sha1").update(f).digest("hex")}function jA(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function ZA(f){return jA(f)&&f.code==="ENOENT"}function WA(f){return jA(f)&&(f.code==="EACCES"||f.code==="EPERM")}class j1{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 Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe(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,Q])=>[J,{...Q}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));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=EL($,()=>{let Q=this.watchedTypesByDirectory.get($);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get($);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:$})})}catch(J){if(!ZA(J)&&!WA(J)){let Q=f.get($);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,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),Q=this.recordsByType.get(f.type)??new Map;for(let[Z,W]of Q.entries()){if($.has(Z))continue;this.emit({kind:"remove",type:f.type,id:Z,filePath:W.filePath})}for(let[Z,W]of $.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let Q of f.directories){J.add(Q);let Z=f.discoverFiles?await f.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:H}=W;if(J.add(W.directoryPath),f.includeFile&&!f.includeFile(j,H))continue;try{let X=await bL(H,"utf8"),A={type:f.type,directoryPath:W.directoryPath,fileName:j,filePath:H,content:X},Y=f.parseFile(A),V=f.resolveId(Y,A).trim();if(!V)continue;$.set(V,{type:f.type,id:V,item:Y,filePath:H,fingerprint:IL(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:X,filePath:H})}}}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 Q of J){let Z=f.get(Q);if(Z)Z.add($);else f.set(Q,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await hL(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:kL(f,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch($){if(ZA($)||WA($))return[];throw $}}}import{readdir as GZ,readFile as xL,stat as PZ}from"node:fs/promises";import{basename as mf,dirname as mL,extname as j5,join as S0,resolve as VJ}from"node:path";import{AGENTS_RULES_FILE_NAME as HA,RULES_CONFIG_DIRECTORY_NAME as Y5,resolveGlobalAgentsRulesPath as gL,resolveRulesConfigSearchPaths as vL,resolveSkillsConfigSearchPaths as cL,resolveWorkflowsConfigSearchPaths as uL,SKILLS_CONFIG_DIRECTORY_NAME as BJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as KJ}from"@cline/shared/storage";import dL from"yaml";var W5="SKILL.md",lL="managed.json",pL=new Set([".md",".markdown",".txt"]);function FZ(f){return f.trim().toLowerCase()}function G2(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"||$?.code==="ELOOP"}function H5(f){return pL.has(j5(f).toLowerCase())}function XA(f){let $=[],J=new Set;for(let Q of f){let Z=VJ(Q);if(J.has(Z))continue;J.add(Z),$.push(Q)}return $}function rL(f){let $=[...f?.directories??UJ(f?.workspacePath)];if(f?.pluginSkillDirectories)$.push(...f.pluginSkillDirectories);else if(f?.includePluginSkills)$.push(...DX({pluginPaths:f.pluginPaths,workspacePath:f.workspacePath,cwd:f.cwd??f.workspacePath}));return XA($)}async function UZ(f){try{let $=await GZ(f,{withFileTypes:!0}),J=[];for(let Q of $){if(!Q.isDirectory())continue;let Z=S0(f,Q.name),W=S0(Z,lL);try{let j=await xL(W,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(G2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch($){if(G2($))return[];throw $}}function RZ(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=dL.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:f,hadFrontmatter:!0,parseError:j}}}function X5(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 Q=f.trim();if(!Q&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return Q||void 0}function F2(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function iL(f,$){if(mf(f.filePath).toLowerCase()!==HA.toLowerCase())return mf(f.filePath,j5(f.filePath));if($&&VJ(f.filePath)===VJ($,HA))return"Workspace AGENTS.md";if(VJ(f.filePath)===VJ(gL()))return"Global AGENTS.md";return mf(f.filePath,j5(f.filePath))}function PJ(f,$){let{data:J,body:Q,parseError:Z}=RZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let H=X5(J.name,"name",!1)??$.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:X5(J.description,"description",!1),disabled:F2(J.disabled,"disabled")??(F2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function GJ(f,$){let{data:J,body:Q,parseError:Z}=RZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=X5(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:F2(J.disabled,"disabled")??(F2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function FJ(f,$){let{data:J,body:Q,parseError:Z}=RZ(f);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=X5(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:F2(J.disabled,"disabled")??(F2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function UJ(f){return cL(f)}function RJ(f){return vL(f)}function DJ(f){return uL(f)}async function AA(f){if(mf(f)===".cline"){let $=await UZ(f);return(await Promise.all($.map((Q)=>AA(S0(Q,BJ))))).flat()}try{let $=await GZ(f,{withFileTypes:!0}),J=[];for(let Q of $){if(Q.isFile()&&Q.name===W5){J.push({directoryPath:f,fileName:Q.name,filePath:S0(f,Q.name)});continue}let Z=S0(f,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await PZ(Z).then((j)=>j.isDirectory()).catch((j)=>{if(G2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:W5,filePath:S0(Z,W5)})}return J}catch($){if(G2($))return[];throw $}}async function A5(f){if(mf(f)===".cline"){let $=await UZ(f);return(await Promise.all($.map((Q)=>A5(S0(Q,"rules.md"))))).flat()}try{if((await PZ(f)).isFile())return[{directoryPath:mL(f),fileName:mf(f),filePath:f}]}catch($){if(!G2($))throw $}try{let J=(await GZ(f,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&H5(Z.name)).map((Z)=>({directoryPath:f,fileName:Z.name,filePath:S0(f,Z.name)})),Q=S0(f,"AGENTS.md");try{if((await PZ(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch($){if(G2($))return[];throw $}}async function nL(f){if(mf(f)===".cline"){let $=await UZ(f);return(await Promise.all($.map((Q)=>A5(S0(Q,KJ))))).flat()}return A5(f)}function LJ(f){let $=rL(f),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?XA([...$,J]):$,discoverFiles:AA,includeFile:(Q)=>Q===W5,parseFile:(Q)=>PJ(Q.content,mf(Q.directoryPath)),resolveId:(Q)=>FZ(Q.name)}}function _J(f){let $=f?.directories??RJ(f?.workspacePath),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:A5,includeFile:(Q,Z)=>Q===".clinerules"||H5(Q)||H5(Z),parseFile:(Q)=>GJ(Q.content,iL(Q,f?.workspacePath)),resolveId:(Q)=>FZ(Q.name)}}function OJ(f){let $=f?.directories??DJ(f?.workspacePath),J=f?.workspacePath?S0(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:nL,includeFile:(Q)=>H5(Q),parseFile:(Q)=>FJ(Q.content,mf(Q.filePath,j5(Q.filePath))),resolveId:(Q)=>FZ(Q.name)}}function YA(f){let $=[LJ(f?.skills),_J(f?.rules),OJ(f?.workflows)];return new j1($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as VA}from"@cline/shared";function aL(f,$){if(f.description?.trim())return VA(f.description,".");if($==="workflow")return;return VA(f.instructions,".")}function tL(f){return f.disabled!==!0}function BA(f,$){return[...f.getSnapshot($).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>tL(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:aL(Q.item,$),kind:$})).sort((J,Q)=>J.name.localeCompare(Q.name))}function TJ(f){let $=new Map;for(let J of[...BA(f,"workflow"),...BA(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function KA(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let Q=J[1];if(!Q)return f;let Z=Q.length+1,W=f.slice(Z),j=TJ($).find((H)=>H.name===Q);return j?`${j.instructions}${W}`:f}var GA={};q(GA,{mergeRulesForSystemPrompt:()=>R2,loadRulesForSystemPromptFromWatcher:()=>DZ,listEnabledRulesFromWatcher:()=>PA,isRuleEnabled:()=>V5,formatRulesForSystemPrompt:()=>U2});function V5(f){return f.disabled!==!0}function U2(f){if(f.length===0)return"";return`
|
|
184
|
+
${Q}`;return J||Q}function XR($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let Q of f){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of f)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of f){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of f){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of f){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of f){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of f)await Q.onEvent?.(J)}}}class Y${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 uQ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??JR,this.conversation=new gQ($.initialMessages),this.messageBuilder=new kQ,this.contributionRegistry=QR({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new cQ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,X)=>YR(this.logger,W,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new vQ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of $)if(!f.has(Q.name))J.push(Q),f.add(Q.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await WR(f);if(J)$.push(J)}return jR(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let F=await BR(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Q=await this.composeSystemPrompt(),Z=LX(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of W)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let X=this.conversation.getConversationId(),Y=yX(this.config),V=Array.from(j.values()),B=KJ(this.conversation.getMessages()),H=NX({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:V,toolContextMetadata:{modelSupportsImages:Y?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[gj]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(Y,V),initialMessages:B,systemPrompt:Q}),A=this.createAgentRuntimeImpl(H);if(this.activeRuntime=A,this.abortRequested)A.abort(this.abortReason);let K=A.subscribe((F)=>{this.handleRuntimeEvent(F)}),G,R;try{if($.isContinue)G=await A.continue(void 0);else G=await A.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let F=ef(G.messages);this.conversation.replaceMessages(F)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=XR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let Q=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=ef(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:KJ(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(GJ($));return KJ(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)f=await Q.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((Y)=>Y.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?ZR(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(ef($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=ef(f).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:f});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:Q,endedAt:Z}=$,W=Z.getTime()-Q.getTime(),j=J?"error":VR(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",Y=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,V=f?ef(f.messages):this.conversation.getMessages(),B=yX(this.config);if(J)throw J;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:B},startedAt:Q,endedAt:Z,durationMs:W}}}function YR($,f,J,Q){if(!$)return;if(f==="debug"){$.debug(J,Q);return}if(f==="error"&&$.error){$.error(J,Q);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...Q,severity:Z})}function VR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function BR($,f,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => wX);return Z($,f,J,Q)}function yX($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=SQ($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as SX}from"@cline/shared";function CX($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return SX({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
|
|
185
|
+
${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function EX($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return SX({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function V$($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function d$($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?CX($.prompt,f):EX($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function B$($){let f=d$($),J=new Y$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var KR=dQ.object({systemPrompt:dQ.string().describe("System prompt defining the sub-agent's behavior"),task:dQ.string().describe("Task for the sub-agent to complete")});function H$($){return HR({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:AR(KR),execute:async(f,J)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=B$({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:X,input:f})}catch{}try{let Y=await Z.run(f.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as X0,TEAM_AWAIT_TIMEOUT_MS as GR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as FR,TEAM_RUN_TEXT_PREVIEW_LIMIT as PR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as DR,TeamAttachOutcomeFragmentInputSchema as hX,TeamAwaitRunsInputSchema as bX,TeamBroadcastInputSchema as kX,TeamBroadcastToolResultSchema as RR,TeamCancelRunInputSchema as IX,TeamCancelRunToolResultSchema as UR,TeamCleanupInputSchema as xX,TeamCleanupToolResultSchema as zR,TeamCreateOutcomeInputSchema as gX,TeamCreateOutcomeToolResultSchema as LR,TeamFinalizeOutcomeInputSchema as mX,TeamFinalizeOutcomeToolResultSchema as _R,TeamListOutcomesInputSchema as vX,TeamListRunsInputSchema as cX,TeamMailboxMessageToolResultSchema as OR,TeamMissionLogInputSchema as uX,TeamMissionLogToolResultSchema as MR,TeamOutcomeFragmentToolResultSchema as dX,TeamOutcomeToolResultSchema as TR,TeamReadMailboxInputSchema as lX,TeamReviewOutcomeFragmentInputSchema as pX,TeamRunTaskInputSchema as rX,TeamRunTaskToolResultSchema as lQ,TeamRunToolSummarySchema as pQ,TeamSendMessageInputSchema as iX,TeamSendMessageToolResultSchema as NR,TeamShutdownTeammateInputSchema as nX,TeamSimpleAgentStatusToolResultSchema as aX,TeamSpawnTeammateInputSchema as sX,TeamStatusInputSchema as tX,TeamStatusToolResultSchema as qR,TeamTaskInputSchema as oX,TeamTaskToolResultSchema as l8,validateWithZod as k,zodToJsonSchema as Y0}from"@cline/shared";function eX($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function l$($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function wR($){let f=$.result;if(!f)return;return{textPreview:eX(f.text,PR),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function PJ($){return $?.toISOString()}function rQ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:eX($.message,FR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:PJ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:PJ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:PJ($.heartbeatAt),lastProgressAt:PJ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:wR($)}}function yR($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var $2=["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 $Y($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...p$({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:d$({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function f2($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,Q=p$({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let W of $.restoredTeammates??[]){if($.runtime.isTeammateActive(W.agentId))continue;$Y({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function p$($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,Z=[];if(J)Z.push(X0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Y0(sX),execute:async(j)=>{let X=k(sX,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if($Y({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Q)$.onLeadToolsUnlocked?.(p$({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return k(aX,{agentId:X.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(X0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Y0(nX),execute:async(j)=>{let X=k(nX,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),k(aX,{agentId:X.agentId,status:"stopped"})}})),Z.push(X0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Y0(tX),execute:async(j)=>{return k(tX,j),k(qR,$.runtime.getSnapshot())}})),Z.push(X0({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:Y0(oX),execute:async(j)=>{let X=k(oX,j);switch(X.action){case"create":{let Y=new Set(DR.create??[]),V=Object.entries(j).filter(([H,A])=>Y.has(H)&&A!=null).map(([H])=>H),B=$.runtime.createTask({title:l$(X.title,"title"),description:l$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return k(l8,{action:"create",taskId:B.id,status:B.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return k(l8,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(l$(X.taskId,"taskId"),$.requesterId);return k(l8,{action:"claim",taskId:Y.id,status:Y.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 Y=$.runtime.completeTask(l$(X.taskId,"taskId"),$.requesterId,l$(X.summary,"summary"));return k(l8,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(l$(X.taskId,"taskId"),$.requesterId,l$(X.reason,"reason"));return k(l8,{action:"block",taskId:Y.id,status:Y.status})}}}}));let W=new Map;return Z.push(X0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Y0(rX),execute:async(j)=>{let X=k(rX,j);if(X.runMode==="async"){let B=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return k(lQ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${B.id}.`,runId:B.id})}let Y=W.get(X.agentId);if(Y){let B=await Y;return k(lQ,{...B,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((B)=>k(lQ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:B.text,iterations:B.iterations})).finally(()=>{W.delete(X.agentId)});return W.set(X.agentId,V),await V}})),Z.push(X0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Y0(IX),execute:async(j)=>{let X=k(IX,j),Y=$.runtime.cancelRun(X.runId,X.reason);return k(UR,{runId:Y.id,status:Y.status})}})),Z.push(X0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Y0(cX),execute:async(j)=>k(pQ.array(),$.runtime.listRuns(k(cX,j)).map(rQ))})),Z.push(X0({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:Y0(bX),timeoutMs:GR,execute:async(j)=>{let X=k(bX,j);if(X.runId){let B=await $.runtime.awaitRun(X.runId);return yR(B),k(pQ,rQ(B))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((B)=>["failed","cancelled","interrupted"].includes(B.status));if(V.length>0){let B=V.map((H)=>`${H.id}:${H.status}${H.error?`(${H.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${B}`)}return k(pQ.array(),Y.map(rQ))}})),Z.push(X0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Y0(iX),execute:async(j)=>{let X=k(iX,j),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return k(NR,{id:Y.id,toAgentId:Y.toAgentId})}})),Z.push(X0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Y0(kX),execute:async(j)=>{let X=k(kX,j),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return k(RR,{delivered:Y.length})}})),Z.push(X0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Y0(lX),execute:async(j)=>{let X=k(lX,j);return k(OR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(X0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Y0(uX),execute:async(j)=>{let X=k(uX,j),Y=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return k(MR,{id:Y.id})}})),Z.push(X0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Y0(xX),execute:async(j)=>{if(k(xX,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),k(zR,{status:"cleaned"})}})),Z.push(X0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Y0(gX),execute:async(j)=>{let X=k(gX,j),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return k(LR,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),Z.push(X0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Y0(hX),execute:async(j)=>{let X=k(hX,j),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return k(dX,{fragmentId:Y.id,status:Y.status})}})),Z.push(X0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Y0(pX),execute:async(j)=>{let X=k(pX,j),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return k(dX,{fragmentId:Y.id,status:Y.status})}})),Z.push(X0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Y0(mX),execute:async(j)=>{let X=k(mX,j),Y=$.runtime.finalizeOutcome(X.outcomeId);return k(_R,{outcomeId:Y.id,status:Y.status})}})),Z.push(X0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Y0(vX),execute:async(j)=>{return k(vX,j),k(TR.array(),$.runtime.listOutcomes())}})),Z}function DJ($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function fY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var SR=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:H$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...$2]}],CR={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function ER($){return $==="plan"||$==="yolo"?$:"act"}function QY($){let f=ER($.mode),J=c0[b1({mode:f})],Q=of($.providerId??"",$.modelId??"",f,tf);return{mode:f,flags:{...J,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function JY($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=QY(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=CR[$];return Q?J[Q]===!0:!1}function hR($,f){if($.id==="editor"){let{flags:J}=QY(f),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:JY($.id,f),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:JY($.id,f)}}function r$($={}){return SR.map((f)=>hR(f,$))}function RJ($={}){return r$($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function UJ($){if(!$.enabled)return new Set;let f=r$($.availabilityContext),J=new Set(f.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function p8($,f={}){return r$(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function zJ($,f={}){return p8($,f)}function i$($={}){let{executorOptions:f={},executors:J,...Q}=$,Z={...sf(f),...J??{}};return j$({...Q,executors:Z})}import{mkdirSync as mR,writeFileSync as vR}from"node:fs";import{dirname as cR}from"node:path";import{normalizeUserInput as uR}from"@cline/shared";import{nanoid as dR}from"nanoid";var WY={};w(WY,{sanitizeSessionToken:()=>n$,parseTeamTaskSubSessionId:()=>Q2,parseSubSessionId:()=>i8,makeTeamTaskSubSessionId:()=>r8,makeSubSessionId:()=>J2,deriveSubsessionStatus:()=>n8});import{nanoid as IR}from"nanoid";function n$($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function J2($,f){let J=n$($),Q=n$(f),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function r8($,f){let J=n$($),Q=n$(f);return`${J}__teamtask__${Q}__${IR(6)}`}function Q2($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),X=Z.slice(W+2);if(!Q||!j||!X)return null;return{rootSessionId:Q,agentId:j,teamTaskId:X}}function i8($){if(Q2($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+f.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function n8($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var YY={};w(YY,{isTerminalSessionStatus:()=>XY,isNonTerminalSessionStatus:()=>W0,SessionSource:()=>P0,SESSION_STATUSES:()=>a8,NON_TERMINAL_SESSION_STATUSES:()=>jY});import{SESSION_STATUS_VALUES as xR}from"@cline/shared";var a8=xR,jY=["idle","running","pending"];function XY($){return!jY.includes($)}function W0($){return!XY($)}var P0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var gR=a.enum(a8),y0=a.object({version:a.literal(1),session_id:a.string().min(1),source:a.string().min(1),pid:a.number().int(),started_at:a.string().min(1),ended_at:a.string().min(1).optional(),exit_code:a.number().int().nullable().optional(),status:gR,interactive:a.boolean(),provider:a.string().min(1),model:a.string().min(1),cwd:a.string().min(1),workspace_root:a.string().min(1),team_name:a.string().min(1).optional(),enable_tools:a.boolean(),enable_spawn:a.boolean(),enable_teams:a.boolean(),prompt:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional(),messages_path:a.string().min(1).optional()});function VY($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function nQ($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function BY($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function k1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function iQ($,f){let J={...$};J.id=k1(J.id)??dR();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:k1(Q?.id)??k1(J.modelId)??k1(f?.id),provider:k1(Q?.provider)??k1(J.providerId)??k1(f?.provider),family:k1(Q?.family)??k1(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function LJ($){return $.map((f)=>iQ(f))}function _J($,f,J=[]){let Q=$.map((Y,V)=>{let B=J[V],A=B?.role===Y.role&&JSON.stringify(B.content)===JSON.stringify(Y.content)?{...B,...Y}:{...Y};return iQ(A)}),Z=J.length,W=[];for(let Y=Z;Y<Q.length;Y+=1)if(Q[Y]?.role==="assistant")W.push(Y);if(W.length===0){let Y=[...Q].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Q;W.push(Q.length-1-Y)}let j=W[W.length-1],X=W.some((Y)=>Q[Y]?.metrics);for(let Y of W){let V=Q[Y],B=V.metrics;if(!B&&Y===j&&!X){let H=f.usage;B={inputTokens:H.inputTokens,outputTokens:H.outputTokens,cacheReadTokens:H.cacheReadTokens??0,cacheWriteTokens:H.cacheWriteTokens??0,cost:H.totalCost}}Q[Y]={...iQ(V,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...B?{metrics:B}:{},ts:V.ts??f.endedAt.getTime()}}return Q}function s8($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var lR=120;function a$($){let f=$?.trim();return f?f.slice(0,lR):void 0}function aQ($){let f=uR($??"").trim();if(!f)return;return a$(f.split(`
|
|
186
|
+
`)[0]?.trim())}function A$($){if(!$)return;let f={...$},J=a$(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function t8($){let f=A$($.metadata)??{},J=$.title!==void 0?a$($.title):aQ($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function sQ($){let f=Q2($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=i8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function tQ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:LJ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function HY($,f,J){mR(cR($),{recursive:!0}),vR($,`${JSON.stringify(tQ({updatedAt:f,context:J,messages:[]}),null,2)}
|
|
187
|
+
`,"utf8")}function AY($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function KY($,f,J){let Q=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let W=await f(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}L0();var GY={};w(GY,{summarizeUsageFromMessages:()=>W2,sumUsageTotals:()=>o8,getCurrentContextSize:()=>oQ,createInitialAccumulatedUsage:()=>K0,accumulateUsageTotals:()=>V0});function K0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function V0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function o8($){let f=K0();for(let J of $)f=V0(f,J);return f}function Z2($){return typeof $==="number"&&Number.isFinite($)?$:0}function W2($){let f=K0();for(let J of $){let Q=J.metrics;if(!Q)continue;f=V0(f,{inputTokens:Z2(Q.inputTokens),outputTokens:Z2(Q.outputTokens),cacheReadTokens:Z2(Q.cacheReadTokens),cacheWriteTokens:Z2(Q.cacheWriteTokens),totalCost:Z2(Q.cost)})}return f}function oQ($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let Q=Z2(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function pR($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function eQ($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function I1($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,Q=$.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function rR($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function iR($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let Q=J?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function $Z($,f,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=$,X=Z.telemetry,Y=W?.runtime.teamRuntime,V=J?.isPrimaryAgentEvent??!0,B=eQ(f),H=I1({agentId:J?.agentId??B.agentId,conversationId:J?.conversationId??B.conversationId,parentAgentId:J?.parentAgentId??B.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??Y?.getTeamId(),teamName:J?.teamName??Y?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let A=pR(f.input);if(A)x6(X,{ulid:Q,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...H})}if(f.type==="content_end"&&f.contentType==="tool"){let A=f.toolName??"unknown",K=!f.error;if(I6(X,{ulid:Q,tool:A,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...H}),!K&&(A==="editor"||A==="apply_patch"))g6(X,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...H})}if(f.type==="notice"&&f.reason==="api_error")Y8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...H});if(f.type==="error")Y8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...H});if(f.type==="usage"&&W?.turnUsageBaseline){let A=rR(f);if(V){W.turnPrimaryUsage=V0(W.turnPrimaryUsage??K0(),A);let G=V0(W.turnUsageBaseline,W.turnPrimaryUsage);$.usageBySession.set(Q,G),xf(X,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...H}),b6(X,{ulid:Q,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...H})}else{let G=iR({isPrimaryAgentEvent:V,overrides:J,eventMetadata:B}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(G,V0(R.get(G)??K0(),A))}let K=V0(W.turnPrimaryUsage??K0(),o8(W.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,V0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if(f.type==="iteration_end"&&V)$.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(V?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:BY(f),ts:Date.now()}})}function K$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as HL}from"@cline/shared";H1();import{existsSync as kJ,readFileSync as dU,statSync as lU}from"node:fs";import{basename as pU,dirname as hJ,join as IJ,resolve as bJ}from"node:path";import{discoverPluginModulePaths as rU,resolveConfiguredPluginModulePaths as lY,resolvePluginConfigSearchPaths as iU,SKILLS_CONFIG_DIRECTORY_NAME as nU}from"@cline/shared/storage";import{resolve as _U}from"node:path";import{normalizePluginManifest as OU}from"@cline/shared";import{existsSync as D0,readFileSync as Y2}from"node:fs";import{builtinModules as QU,createRequire as WZ}from"node:module";import{dirname as G$,extname as J4,isAbsolute as ZU,resolve as p}from"node:path";import{fileURLToPath as TY}from"node:url";import{PLUGIN_FILE_EXTENSIONS as WU}from"@cline/shared";var NY=G$(TY(import.meta.url)),jU=WZ(import.meta.url),XU=p(NY,"..","..","..","..",".."),JZ=BU(XU),YU=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],jZ=new Set(QU.flatMap(($)=>[$,$.replace(/^node:/,"")])),f4=new Set(WU),VU=["development","node","import","require","default"];function BU($){let f={},J={"@cline/sdk":p($,"packages/sdk/src/index.ts"),"@cline/agents":p($,"packages/agents/src/index.ts"),"@cline/core":p($,"packages/core/src/index.ts"),"@cline/llms":p($,"packages/llms/src/index.ts"),"@cline/shared":p($,"packages/shared/src/index.ts"),"@cline/shared/storage":p($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":p($,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(D0(Z))f[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=p($,"packages",Q),W=p(Z,"package.json");if(!D0(W))continue;try{let j=JSON.parse(Y2(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=p(Z,j.exports);if(D0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,Y]of Object.entries(j.exports)){let V=HU(Z,Y);if(!V)continue;let B=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[B]=V}}catch{}}return f}function HU($,f){let J=XZ(f);if(!J)return null;let Q=qY($,J);for(let Z of Q)if(D0(Z))return Z;return null}function XZ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let Q of VU){let Z=XZ(J[Q],f);if(Z)return Z}return null}function qY($,f){let J=f.replace(/^\.\//,""),Q=[p($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[p($,`${Z}.ts`),p($,`${Z}.tsx`),p($,`${Z}.mts`),p($,`${Z}.cts`),...Q]}return Q}function AU($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function yJ($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function X2($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function KU($){let f=X2($);if($===f)return".";return`.${$.slice(f.length)}`}function wY($){return X2($).startsWith("@cline/")}function QZ($,f){let J=X2(f),Q=G$($);while(!0){let Z=p(Q,"node_modules",J);if(D0(Z)||D0(p(Z,"package.json")))return!0;let W=p(Q,"..");if(W===Q)return!1;Q=W}}function MY($){return ZZ($)!==null}function ZZ($){try{return jU.resolve($)}catch{}return GU($)}function GU($){let f=X2($),J=yY(f);if(!J)return null;let Q=p(J,"package.json");try{let Z=JSON.parse(Y2(Q,"utf8")),W=KU($),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,X=XZ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let Y=p(J,X),V=[Y,...qY(J,X).filter((B)=>B!==Y)];for(let B of V)if(D0(B))return B;return null}catch{return null}}function FU(){let $=[NY],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(G$(G$(f)));let J=process.execPath?.trim();if(J)$.push(G$(J));return[...new Set($.map((Q)=>p(Q)))]}function PU($,f){let J=$;while(!0){let Q=p(J,"package.json");if(D0(Q))try{if(JSON.parse(Y2(Q,"utf8")).name===f)return J}catch{}let Z=p(J,"node_modules",f,"package.json");if(D0(Z))return G$(Z);let W=p(J,"..");if(W===J)return null;J=W}}function yY($){for(let f of FU()){let J=PU(f,$);if(J)return J}return null}function DU($){let J=G$($);for(let Q=0;Q<4;Q++){let Z=p(J,"package.json");if(D0(Z))try{let j=JSON.parse(Y2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=p(J,"..");if(W===J)return!1;J=W}return!1}function SY($,f){let J=f.startsWith("file:")?TY(f):ZU(f)?f:p(G$($),f);if(D0(J)&&f4.has(J4(J)))return J;for(let Q of f4){let Z=`${J}${Q}`;if(D0(Z))return Z}for(let Q of f4){let Z=p(J,`index${Q}`);if(D0(Z))return Z}return null}function CY($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of $.matchAll(Q)){let W=Z[1];if(W)f.add(W)}return[...f]}function RU($){return J4($)!==".ts"}function EY($,f,J=new Set){if(J.has($)||!D0($))return;if(J.add($),!f4.has(J4($)))return;let Q=Y2($,"utf8"),Z=RU($);for(let W of CY(Q)){if(W.startsWith("node:")||jZ.has(W))continue;if(yJ(W)){if(!Z)continue;if(Object.hasOwn(JZ,W)||Object.hasOwn(JZ,X2(W))||QZ($,W)||wY(W)&&MY(W)||f&&MY(W))continue;throw Error(`Cannot find module '${X2(W)}'`)}let j=SY($,W);if(j)EY(j,f,J)}}function hY($,f=new Set,J=new Set){if(f.has($)||!D0($))return J;if(f.add($),!f4.has(J4($)))return J;let Q=Y2($,"utf8");for(let Z of CY(Q)){if(J.add(Z),yJ(Z))continue;let W=SY($,Z);if(W)hY(W,f,J)}return J}function UU($,f){let J=WZ($),Q={},Z=hY($),W=new Set(YU);for(let[j,X]of Object.entries(JZ)){try{J.resolve(j);continue}catch{}Q[j]=X}for(let j of Z)if(yJ(j)&&(wY(j)||f))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||QZ($,j))continue;let X=ZZ(j);if(X)Q[j]=X}if(!f)return Q;for(let j of Z){if(!yJ(j)||Object.hasOwn(Q,j)||QZ($,j)||j.startsWith("node:")||jZ.has(j))continue;let X=ZZ(j);if(X)Q[j]=X}return Q}function zU($){let f=J4($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var t$;function LU(){if(t$!==void 0)return t$;let $=yY("jiti");if(!$)return t$=null,null;let f=p($,"dist","babel.cjs");if(!D0(f))return t$=null,null;try{let Q=WZ(f)(f);t$=typeof Q==="function"?Q:null}catch{t$=null}return t$}async function bY($,f={}){let J=!DU($);EY($,J);let Q=UU($,J),Z=AU(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,H])=>zU(H)).map(([H])=>H),Y=LU(),V=Y?(H)=>Y({...H,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...jZ],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function kY($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function IY($){return typeof $==="object"&&$!==null}function YZ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function MU($,f){if(!IY($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!YZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!YZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!YZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function TU($,f){if(!IY($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);MU($,f)}async function Q4($,f={}){let J=_U(f.cwd??process.cwd(),$),Q=await bY(J,{useCache:f.useCache}),Z=f.exportName??"plugin",W=Q.default??Q[Z];TU(W,J);let j=W,X=j.setup,Y=X?(V,B)=>{let H={...f.session,...B.session},A={...B,session:Object.keys(H).length>0?H:void 0,client:f.client??B.client,user:f.user??B.user,workspaceInfo:f.workspaceInfo??B.workspaceInfo,automation:f.automation??B.automation,logger:f.logger??B.logger,telemetry:f.telemetry??B.telemetry};return X(V,A)}:void 0;return{...j,manifest:OU(j.manifest),setup:Y}}async function SJ($,f={}){return(await o$($,f)).plugins}async function o$($,f={}){let J=[],Q=[],Z=new Map,W=0;for(let X of $)try{let Y=await Q4(X,f);if(!kY(Y.manifest,f))continue;let V=Z.get(Y.name);if(V)Q.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});Z.set(Y.name,{plugin:Y,pluginPath:X,order:W++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);J.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let j=[...Z.values()].sort((X,Y)=>X.order-Y.order);return{plugins:j.map((X)=>X.plugin),pluginPaths:j.map((X)=>X.pluginPath),failures:J,warnings:Q}}import{existsSync as AZ}from"node:fs";import{createRequire as dY}from"node:module";import{dirname as CJ,join as B2}from"node:path";import{fileURLToPath as SU}from"node:url";var cY={};w(cY,{resolveSubprocessRuntimeExecutable:()=>VZ,buildSubprocessSandboxCommand:()=>vY,SubprocessSandbox:()=>V2,CLINE_JS_RUNTIME_PATH_ENV:()=>mY});import{spawn as NU}from"node:child_process";import{basename as qU}from"node:path";import{augmentNodeCommandForDebug as wU,withResolvedClineBuildEnv as yU}from"@cline/shared";function xY($){if($ instanceof Error)return $;return Error(String($))}var mY="CLINE_JS_RUNTIME_PATH";function gY($){let f=$?.trim();if(!f)return!1;let J=qU(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function VZ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[mY]?.trim();if(J)return J;let Q=$.execPath?.trim()||process.execPath;if(gY(Q))return Q;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let W=Z?.trim();if(W&&gY(W))return W}return"node"}function vY($,f={}){let J=VZ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return wU([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class V2{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=vY($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=NU(f[0]??VZ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:yU(process.env),windowsHide:!0});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${xY(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let X=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let Y={resolve:(V)=>j(V),reject:X};if((J.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,Y),Q.send(W,(V)=>{if(!V)return;let B=this.clearPendingRequest(Z);if(!B)return;B.reject(Error(`${this.processLabel} failed to send call "${$}": ${xY(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function CU($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Z4($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function EU(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function hU(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=dY($).resolve(`${EU()}/package.json`),Q=B2(CJ(J),"extensions","plugin-sandbox-bootstrap.js");return AZ(Q)?Q:void 0}catch{return}}function bU(){let $=process.execPath?.trim();if(!$)return;let f=B2(CJ(CJ($)),"extensions","plugin-sandbox-bootstrap.js");return AZ(f)?f:void 0}function kU(){let $=CJ(SU(import.meta.url)),f=dY(import.meta.url),J=[B2($,"plugin-sandbox-bootstrap.js"),B2($,"extensions","plugin-sandbox-bootstrap.js"),B2($,"agents","plugin-sandbox-bootstrap.js"),hU(),bU()];for(let W of J.filter((j)=>typeof j==="string"))if(AZ(W))return{file:W};let Q=B2($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
188
|
+
`)}}var BZ=kU();function HZ($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let Q=process.env[J];if(Q){let Z=Number(Q);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function EJ($){let f=new V2({name:"plugin-sandbox",..."file"in BZ?{bootstrapFile:BZ.file}:{bootstrapScript:BZ.script},onEvent:$.onEvent}),J=HZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=HZ($.hookTimeoutMs,3000),Z=HZ($.contributionTimeoutMs,60000),W={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},Y;try{Y=await f.call("initialize",W,{timeoutMs:J})}catch(H){throw await f.shutdown().catch(()=>{}),H}let V=Y.plugins.map(CU);return{extensions:V.map((H)=>{let A={name:H.name,__clinePluginPath:H.pluginPath,manifest:H.manifest,setup:(K)=>{IU(K,f,H,Z,X),xU(K,f,H,Z,X),gU(K,f,H,Z,X),vU(K,f,H,Z,X),mU(K,H)}};return A.hooks=uU(f,H,Q,X),A}),failures:Y.failures,pluginPaths:V.map((H)=>H.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:Y.warnings}}function IU($,f,J,Q,Z){for(let W of J.contributions?.tools??[]){let j={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(X,Y)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:Y},{timeoutMs:Q})}catch(V){if(!Z4(V))throw V;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:Y},{timeoutMs:Q})}}};$.registerTool(j)}}function xU($,f,J,Q,Z){for(let W of J.contributions?.commands??[])$.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(X){if(!Z4(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function gU($,f,J,Q,Z){for(let W of J.contributions?.rules??[])$.registerRule({id:W.ruleId,source:W.source,content:W.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}catch(j){if(!Z4(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:W.id},{timeoutMs:Q})}}:W.content??""})}function mU($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function vU($,f,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:W.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return uY(X)?X:j}catch(X){if(!Z4(X))throw X;await Z();let Y=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return uY(Y)?Y:j}}})}function uY($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function cU($,f,J,Q,Z){return async(W)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!Z4(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}}}function uU($,f,J,Q){let Z={};for(let W of f.hooks??[])Z[W]=cU($,f.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}var GZ="package.json",aU="package";function W4($){return iU($)}function j4($){return rU($)}function sU($){try{return kJ($)&&lU($).isDirectory()}catch{return!1}}function FZ($){let f=[],J=new Set;for(let Q of $){let Z=bJ(Q);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function pY($){let f=FZ($);return qJ(f)}function rY($){return W4($).flatMap((f)=>j4(f)).filter((f)=>kJ(f))}function tU($,f){let J=[];for(let Q of $)try{J.push(...lY([Q],f))}catch{}return J}function KZ($){return typeof $==="object"&&$!==null}function oU($){try{let f=JSON.parse(dU(IJ($,GZ),"utf8"));if(!KZ(f)||!KZ(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(typeof Z==="string"){Q.push(Z);continue}if(!KZ(Z)||!Array.isArray(Z.paths))continue;for(let W of Z.paths)if(typeof W==="string")Q.push(W)}return Q}catch{return[]}}function iY($,f){let J=bJ(f);return oU($).some((Q)=>bJ($,Q)===J)}function eU($,f){return pU($)===aU&&kJ(IJ(hJ($),GZ))&&iY(hJ($),f)}function $z($){let f=bJ($),J=[],Q=hJ(f);while(!0){if(eU(Q,f)){J.push(Q);break}if(kJ(IJ(Q,GZ))){if(iY(Q,f))J.push(Q);break}let Z=hJ(Q);if(Z===Q)break;Q=Z}return FZ(J)}function e$($={}){let f=$.cwd??process.cwd(),J=rY($.workspacePath),Q=lY($.pluginPaths??[],f);return pY([...Q,...J])}function fz($={}){let f=$.cwd??process.cwd(),J=rY($.workspacePath),Q=tU($.pluginPaths??[],f);return pY([...Q,...J])}function $f($){let f=[];for(let J of $)for(let Q of $z(J)){let Z=IJ(Q,nU);if(sU(Z))f.push(Z)}return FZ(f)}function nY($={}){return $f(fz($))}async function H2($={}){let f=e$($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await o$(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let J=await EJ({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as Jz}from"node:child_process";import{promisify as Qz}from"node:util";var Zz=Qz(Jz);function PZ($,f){$?.log(f,{severity:"warn"})}function Wz($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let Q=J.latest,Z=J.history.filter((W)=>!!W&&typeof W==="object"&&typeof W.ref==="string"&&typeof W.createdAt==="number"&&typeof W.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:Z}}async function ff($,f){let J=await Zz("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function DZ($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:Q}=await ff($,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
|
|
189
|
+
`).filter(Boolean);await Promise.allSettled(Z.map((W)=>ff($,["update-ref","-d",W])))}catch{}}async function aY($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((Q)=>ff($,["update-ref",`refs/cline/checkpoints/${f}/${Q.runCount}`,Q.ref])))}function jz($,f){let J=$.findIndex((Q)=>Q.runCount===f.runCount);if(J<0)return[...$,f];return $.map((Q,Z)=>Z===J?f:Q)}function sY($){let f=$.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await ff($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await Q())return;let W=async(V)=>{try{let H=(await ff($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!H)return;return{ref:H,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(B){PZ($.logger,`${V}: ${B instanceof Error?B.message:String(B)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await ff($.cwd,["stash","create",j])).stdout.trim()}catch(V){return PZ($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),W("Checkpoint HEAD fallback failed")}if(!X)return W("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await ff($.cwd,["update-ref",Y,X])}catch(V){PZ($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),Y=Wz(X);if(Y?.latest.ref===j.ref)return;let V=jz(Y?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:V}});return}}}import{spawn as Fz}from"node:child_process";import{appendFileSync as Pz,readFileSync as Dz}from"node:fs";import{join as Rz}from"node:path";import{augmentNodeCommandForDebug as eY,withResolvedClineBuildEnv as zZ}from"@cline/shared";import{ensureHookLogDir as tY}from"@cline/shared/storage";function A2($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as Xz,readdirSync as Yz}from"node:fs";import{basename as Vz,extname as Bz,join as Hz}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as xJ,resolveHooksConfigSearchPaths as Az}from"@cline/shared/storage";function X4($){return Az($)}var K2;((B)=>{B.TaskStart="TaskStart";B.TaskResume="TaskResume";B.TaskCancel="TaskCancel";B.TaskComplete="TaskComplete";B.TaskError="TaskError";B.PreToolUse="PreToolUse";B.PostToolUse="PostToolUse";B.UserPromptSubmit="UserPromptSubmit";B.PreCompact="PreCompact";B.SessionShutdown="SessionShutdown"})(K2||={});var Y4={["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"},Kz=new Map(Object.values(K2).map(($)=>[$.toLowerCase(),$])),Gz=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function V4($){let f=Bz($).toLowerCase();if(!Gz.has(f))return;let J=Vz($,f).trim().toLowerCase();return Kz.get(J)}function F$($){let f=[],J=new Set,Q=X4($).filter((Z)=>Xz(Z));for(let Z of Q)try{for(let W of Yz(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=V4(W.name);if(!j)continue;let X=Hz(Z,W.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:Y4[j],path:X})}}catch{}return f.sort((Z,W)=>Z.path.localeCompare(W.path))}function mJ($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))f[J]=typeof Q==="string"?Q:JSON.stringify(Q);return f}function gJ($,f,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${f}${Q}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function Uz($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
|
|
190
|
+
`),Q=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function zz($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function RZ($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function R0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function Lz($){let f=$.trim();if(!f)return{};let Q=f.split(`
|
|
191
|
+
`).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function _z($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",Y),J.off("finish",V),$.off("close",B)},X=(H)=>{if(W)return;if(W=!0,j(),H){let A=H.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Q();return}Z(H);return}Q()},Y=(H)=>X(H),V=()=>X(),B=()=>X();J.on("error",Y),J.once("finish",V),$.once("close",B);try{J.end(f)}catch(H){X(H)}})}async function $V($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await oY($,f)}catch(J){let Q=Tz(f.command,process.platform,J);if(!Q)throw J;return await oY($,{...f,command:Q})}}async function oY($,f){let J=eY(f.command,{env:f.env,debugRole:"hook"}),Q=Fz(J[0],J.slice(1),{cwd:f.cwd,env:zZ(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached,windowsHide:!0}),Z=new Promise((A)=>{Q.once("spawn",()=>A())}),W=new Promise((A,K)=>{Q.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,W]),await _z(Q,j),f.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,B;Q.stdout.on("data",(A)=>{X+=A.toString()}),Q.stderr.on("data",(A)=>{Y+=A.toString()});let H=new Promise((A)=>{if((f.timeoutMs??0)>0)B=setTimeout(()=>{V=!0,Q.kill("SIGKILL")},f.timeoutMs);Q.once("close",(K)=>{if(B)clearTimeout(B);let{parsedJson:G,parseError:R}=Lz(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([H,W])}function Oz($){try{let J=Dz($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let Q=J.slice(2).trim();if(!Q)return;let Z=Q.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function Mz($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function Tz($,f=process.platform,J){if(f!=="win32"||!Mz(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function fV($){if($.length===0)return;let[f,...J]=$,Q=f.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return fV(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function Nz($){let f=Oz($);if(f&&f.length>0)return[...fV(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return eY(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function qz($){let f={};for(let J of F$($)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=f[Q]??[];Z.push(Nz(J.path)),f[Q]=Z}return f}async function wz($){let f;for(let J of $.commands){let Q=J.join(" ");try{let Z=await $V($.payload,{command:J,cwd:$.cwd,env:zZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){gJ($.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){gJ($.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}f=Uz(f,zz(Z?.parsedJson))}catch(Z){gJ($.logger,`hook command failed: ${Q}`,Z)}}return f}function Jf($){for(let f of $.commands){let J=f.join(" ");$V($.payload,{command:f,cwd:$.cwd,env:zZ(process.env),detached:!0}).catch((Q)=>{gJ($.logger,`hook command failed: ${J}`,Q)})}}function P$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function UZ($,f){return{...P$($.snapshot),userMessage:f}}function JV($){return{...P$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function QV($){return{...P$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function ZV($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function yz($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function G2($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
|
|
192
|
+
`,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Rz(tY(),"hooks.jsonl");tY(j),Pz(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=UZ(Q,"");J({...R0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=JV(Q);J({...R0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:mJ(Z.call.input)}});return},afterTool:async(Q)=>{let Z=QV(Q);J({...R0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:mJ(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:Q,result:Z})=>{let W=P$(Q);if(Z.status==="completed"){J({...R0(W,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||RZ(Z.error?.message)){J({...R0(W,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...R0(W,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=UZ({snapshot:Q.snapshot},ZV(Q.message.content));J({...R0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function B4($){let f=qz($.workspacePath);if(!Object.values(f).some((H)=>H.length>0))return;let Q=async(H,A)=>{let K=f[A]??[];if(K.length===0)return;Jf({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...R0(H,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...R0(H,$),hookName:A,taskStart:{taskMetadata:{}}}})},Z=async(H)=>{let A=f.prompt_submit??[];if(A.length>0)Jf({commands:A,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}}})},W=async(H)=>{let A=f.tool_call??[];if(A.length===0)return;return wz({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...R0(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:mJ(H.call.input)}}})},j=async(H)=>{let A=f.tool_result??[];if(A.length===0)return;Jf({commands:A,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:mJ(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}}})},X=async(H)=>{let A=f.agent_end??[];if(A.length===0)return;Jf({commands:A,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"agent_end",iteration:H.iteration,turn:H.turn,taskComplete:{taskMetadata:{}}}})},Y=async(H)=>{let A=f.agent_error??[];if(A.length===0)return;Jf({commands:A,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"agent_error",iteration:H.iteration,error:{name:H.error.name,message:H.error.message,stack:H.error.stack}}})},V=async(H)=>{if(RZ(H.reason)){let K=f.agent_abort??[];if(K.length>0)Jf({commands:K,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"agent_abort",reason:H.reason,taskCancel:{taskMetadata:{}}}})}let A=f.session_shutdown??[];if(A.length===0)return;Jf({commands:A,cwd:$.cwd,logger:$.logger,payload:{...R0(H,$),hookName:"session_shutdown",reason:H.reason}})},B={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)B.beforeRun=async(H)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(P$(H.snapshot),A);return};if((f.prompt_submit?.length??0)>0)B.onEvent=async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;await Z(UZ({snapshot:H.snapshot},ZV(H.message.content)))}}if((f.tool_call?.length??0)>0)B.beforeTool=async(H)=>{let A=await W(JV(H));return yz(A)};if((f.tool_result?.length??0)>0)B.afterTool=async(H)=>{await j(QV(H));return};if((f.agent_end?.length??0)>0)B.afterRun=async({snapshot:H,result:A})=>{if(A.status!=="completed")return;await X({...P$(H),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let H=B.afterRun;B.afterRun=async(A)=>{await H?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||RZ(G.error?.message)){await V({...P$(K),reason:G.error?.message});return}if(G.error)await Y({...P$(K),iteration:G.iterations,error:G.error})}}return B}function F2($){return A2("core.hook_config_files",B4($))}function Qf($,f){let J=$.map((Q)=>Q[f]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function Zf($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:Qf(f,"beforeRun"),afterRun:Qf(f,"afterRun"),beforeModel:Qf(f,"beforeModel"),afterModel:Qf(f,"afterModel"),beforeTool:Qf(f,"beforeTool"),afterTool:Qf(f,"afterTool"),onEvent:Qf(f,"onEvent")}}var WV={};w(WV,{normalizeRuntimeCapabilities:()=>U0});function U0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=f&&Object.keys(f).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var GV={};w(GV,{toProviderConfig:()=>d0,emptyStoredProviderSettings:()=>U$,StoredProviderSettingsSchema:()=>U2,StoredProviderSettingsEntrySchema:()=>Y5,ProviderSettingsSchemaTyped:()=>R2});import{z as R$}from"zod";var KV={};w(KV,{toProviderConfig:()=>d0,safeParseSettings:()=>X5,safeCreateProviderConfig:()=>SZ,parseSettings:()=>j5,normalizeProviderId:()=>D2,isBuiltInProviderId:()=>wZ,createProviderConfig:()=>yZ,SapSettingsSchema:()=>Q5,ReasoningSettingsSchema:()=>eJ,ProviderSettingsSchema:()=>D$,ProviderProtocolSchema:()=>sJ,ProviderIdSchema:()=>F4,ProviderClientSchema:()=>tJ,OcaSettingsSchema:()=>Z5,ModelCatalogSettingsSchema:()=>W5,GcpSettingsSchema:()=>f5,BUILT_IN_PROVIDER_IDS:()=>qZ,BUILT_IN_PROVIDER:()=>G4,AzureSettingsSchema:()=>J5,AwsSettingsSchema:()=>$5,AuthSettingsSchema:()=>oJ});import*as u0 from"@cline/llms";import{z as q}from"zod";var AV={};w(AV,{resolveProviderConfig:()=>K4,getProviderConfig:()=>aJ,getLiveModelsCatalog:()=>P2,clearPublicModelsCatalogCache:()=>sz,clearPrivateModelsCatalogCache:()=>NZ,clearLiveModelsCatalogCache:()=>TZ,OPENAI_COMPATIBLE_PROVIDERS:()=>A4,DEFAULT_MODELS_CATALOG_URL:()=>pJ});import*as B0 from"@cline/llms";function LZ($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((f)=>f.length>0)}function Sz($,f){let J=LZ($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let Q=$,Z=LZ(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[f];if(W&&typeof W==="object"){let X=LZ(W.models??W);if(X.length>0)return X}return[]}async function vJ($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return Sz(await J.json(),f)}function jV($){return $.replace(/\/+$/,"")}function cJ($,f,J){let Q=J?.trim();if(!Q)return;let Z=$?.trim();if(!Z||!f?.trim())return Q;try{let W=new URL(Q),j=new URL(f),X=new URL(Z);if(W.origin!==j.origin)return Q;let Y=jV(j.pathname),V=jV(X.pathname);if(Y&&W.pathname.startsWith(`${Y}/`)){let B=W.pathname.slice(Y.length);X.pathname=`${V}${B}`}else X.pathname=W.pathname;return X.search=W.search,X.hash=W.hash,X.toString()}catch{return Q}}function Cz($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function Ez($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var hz=Object.values(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:Cz($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),YV=Object.fromEntries(hz.map(($)=>[$.id,$]));function bz($){return YV[$]}function kz(){return Object.fromEntries(Object.entries(YV).filter(([,$])=>Ez($)))}function VV($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var pJ="https://models.dev/api.json",Iz=600000,BV=300000,xz=5000,lJ=new Map,H4=new Map,_Z=new Map,uJ=new Map;async function gz(){return B0.getGeneratedProviderModels()}async function mz($,f={},J={},Q={},Z={},W={}){let j=await gz(),X=B0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((H)=>j[H]??{})),V=Boolean(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),B=Object.keys(Z).length>0;if(V&&B)return B0.sortModelsByReleaseDate({...Z,...W});if($==="openai-codex")return B0.sortModelsByReleaseDate({...f,...B0.filterOpenAICodexModels(J),...Z,...W});return B0.sortModelsByReleaseDate({...Y,...f,...J,...Q,...Z,...W})}function vz($,f){let J=B0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((Q)=>f[Q]??{}))}function rJ($){let f=$?.trim();return f&&f.length>0?f:""}function MZ($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function cz($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function uz($,f){return`${$}:${rJ(f.baseUrl)}:${cz(MZ(f)??"")}`}async function iJ($,f,J=xz){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch($,{...f,signal:Q.signal})}finally{clearTimeout(Z)}}function Wf($,f,J){if(J&&!$.includes(f))$.push(f)}function nJ($,f){let J=["streaming","tools"];return Wf(J,"images",Boolean(f.supportsImages)),Wf(J,"prompt-cache",Boolean(f.supportsPromptCache)),Wf(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function dz($,f){let J=await iJ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=j.supported_features??[];W[X]=nJ(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return W}function XV($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function lz($,f){let J=await iJ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;W[X]=nJ(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function pz($,f){let Q=`${(rJ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await iJ(Q,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let Y of j){let V=Y.id?.trim();if(!V)continue;let B=Y.supported_features??[],H=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];Wf(K,"tools",B.includes("tools")),Wf(K,"reasoning",B.includes("reasoning")),Wf(K,"temperature",H.includes("temperature")),Wf(K,"images",A.includes("image"));let G={input:XV(Y.pricing?.prompt),output:XV(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function rz($){let f=rJ($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function iz($,f){let Q=`${rz($.baseUrl)}/v1/model/info`,Z=async(V)=>iJ(Q,{method:"GET",headers:{accept:"application/json",...V}}),W=await Z({"x-litellm-api-key":f});if(!W.ok)W=await Z({Authorization:`Bearer ${f}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let X=(await W.json())?.data??[],Y={};for(let V of X){let B=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||B;if(!A)continue;let K=V.model_info,G=nJ(A,{name:B??A,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(Y[A]=G,B)Y[B]={...G,id:B,name:B}}return Y}var HV={baseten:dz,hicap:lz,litellm:iz,poolside:pz},OZ=new Map,dJ=new Map;function nz($,f){return`${$}:${rJ(f.baseUrl)}`}async function az($,f,J){let Q=B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=cJ(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=f?.cacheTtlMs??BV,j=nz($,J),X=Date.now(),Y=OZ.get(j);if(Y&&Y.expiresAt>X)return Y.data;let V=dJ.get(j);if(V)return V;let B=vJ(Z,$).then((H)=>{let A=Object.fromEntries(H.map((K)=>[K,nJ(K,{name:K})]));return OZ.set(j,{data:A,expiresAt:X+W}),A}).finally(()=>{dJ.delete(j)});return dJ.set(j,B),B}function sz(){OZ.clear(),dJ.clear()}async function tz($,f){let J=MZ(f);if(!J)return{};let Q=HV[$];if(!Q)return{};return Q(f,J)}function oz($,f,J){if(!J)return!1;if(!HV[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(MZ(J))}async function ez($,f,J){let Q=f?.cacheTtlMs??BV,Z=uz($,J),W=Date.now(),j=_Z.get(Z);if(j&&j.expiresAt>W)return j.data;let X=uJ.get(Z);if(X)return X;let Y=tz($,J).then((V)=>{return _Z.set(Z,{data:V,expiresAt:W+Q}),V}).finally(()=>{uJ.delete(Z)});return uJ.set(Z,Y),Y}async function $L($){return B0.fetchModelsDevProviderModels($,globalThis.fetch)}async function P2($={}){let f=$.url??pJ,J=$.cacheTtlMs??Iz,Q=Date.now(),Z=lJ.get(f);if(Z&&Z.expiresAt>Q)return Z.data;let W=H4.get(f);if(W)return W;let j=$L(f).then((X)=>{return lJ.set(f,{data:X,expiresAt:Q+J}),X}).finally(()=>{H4.delete(f)});return H4.set(f,j),j}function TZ($){if($){lJ.delete($),H4.delete($);return}lJ.clear(),H4.clear()}function NZ(){_Z.clear(),uJ.clear()}function fL($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:VV(J.capabilities)}]))}var A4=fL(kz());function aJ($){let f=bz($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:VV(f.capabilities)}}async function K4($,f,J){let Q=aJ($);if(!Q)return;try{let Z=f?.loadLatestOnInit?await P2(f):void 0,W=Z?vz($,Z):{},j=J&&oz($,f,J)?await ez($,f,J):{},Y=Boolean(B0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,V=Y?await az($,f,Y).catch(()=>({})):{},B=await mz($,Q.knownModels,W,j,V,J?.knownModels);return{...Q,knownModels:B}}catch(Z){if(f?.failOnError)throw Z;return Q}}var G4=u0.BUILT_IN_PROVIDER,qZ=u0.BUILT_IN_PROVIDER_IDS,wZ=u0.isBuiltInProviderId,D2=u0.normalizeProviderId,F4=q.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),sJ=q.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),tJ=q.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),oJ=q.object({apiKey:q.string().optional(),accessToken:q.string().optional(),refreshToken:q.string().optional(),expiresAt:q.number().int().positive().optional(),accountId:q.string().optional()}),JL=q.enum(["none","low","medium","high","xhigh"]),eJ=q.object({enabled:q.boolean().optional(),effort:JL.optional(),budgetTokens:q.number().int().positive().optional()}),$5=q.object({accessKey:q.string().optional(),secretKey:q.string().optional(),sessionToken:q.string().optional(),region:q.string().optional(),profile:q.string().optional(),authentication:q.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:q.boolean().optional(),useCrossRegionInference:q.boolean().optional(),useGlobalInference:q.boolean().optional(),endpoint:q.string().url().optional(),customModelBaseId:q.string().optional()}),f5=q.object({projectId:q.string().optional(),region:q.string().optional()}),J5=q.object({apiVersion:q.string().optional(),useIdentity:q.boolean().optional()}),Q5=q.object({clientId:q.string().optional(),clientSecret:q.string().optional(),tokenUrl:q.string().url().optional(),resourceGroup:q.string().optional(),deploymentId:q.string().optional(),useOrchestrationMode:q.boolean().optional(),api:q.enum(["orchestration","foundation-models"]).optional(),defaultSettings:q.record(q.string(),q.unknown()).optional()}),Z5=q.object({mode:q.enum(["internal","external"]).optional(),usePromptCache:q.boolean().optional()}),W5=q.object({loadLatestOnInit:q.boolean().optional(),loadPrivateOnAuth:q.boolean().optional(),url:q.string().url().optional(),cacheTtlMs:q.number().int().positive().optional(),failOnError:q.boolean().optional()}),D$=q.object({provider:F4,apiKey:q.string().optional(),auth:oJ.optional(),model:q.string().optional(),protocol:sJ.optional(),client:tJ.optional(),routingProviderId:F4.optional(),maxTokens:q.number().int().positive().optional(),contextWindow:q.number().int().positive().optional(),baseUrl:q.string().url().optional(),headers:q.record(q.string(),q.string()).optional(),timeout:q.number().int().positive().optional(),reasoning:eJ.optional(),aws:$5.optional(),gcp:f5.optional(),azure:J5.optional(),sap:Q5.optional(),oca:Z5.optional(),region:q.string().optional(),apiLine:q.enum(["china","international"]).optional(),capabilities:q.array(q.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:W5.optional()});function j5($){return D$.parse($)}function X5($){return D$.safeParse($)}function QL($){return $.protocol==="openai-responses"||$.client==="openai"}function d0($,f={}){let J=$.provider,Q=D2(J),Z=f.includeKnownModels!==!1,W=$.reasoning?.effort||"none",j=W==="none"?void 0:W,X=A4[Q],Y=Object.assign({},...u0.resolveProviderModelCatalogKeys(Q).map((R)=>u0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],B=df(Q,$),H=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?o6:e6:X?.baseUrl),A=$.routingProviderId??(QL($)&&Q!==G4.OPENAI_NATIVE?G4.OPENAI_NATIVE:void 0),K=Z?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...Z?{knownModels:K}:{},apiKey:B,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:H,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,P])=>P!==void 0))}function yZ($){let f=j5($);return d0(f)}function SZ($){let f=X5($);if(f.success)return{success:!0,config:d0(f.data)};return{success:!1,error:f.error}}var R2=D$;var Y5=R$.object({settings:D$,updatedAt:R$.string().datetime(),tokenSource:R$.enum(["manual","oauth","migration"]).default("manual")}),U2=R$.object({version:R$.literal(1),lastUsedProvider:R$.string().min(1).optional(),providers:R$.record(R$.string(),Y5)});function U$(){return{version:1,providers:{}}}H1();var RV={};w(RV,{InMemoryWorkspaceManager:()=>L2});import{upsertWorkspaceInfo as XL,WorkspaceManifestSchema as EZ}from"@cline/shared";var DV={};w(DV,{normalizeWorkspacePath:()=>g1,generateWorkspaceInfoWithDiagnostics:()=>P4,generateWorkspaceInfo:()=>z2,buildWorkspaceMetadataWithInfo:()=>CZ,buildWorkspaceMetadata:()=>D4});import{basename as ZL,resolve as WL}from"node:path";import{performance as FV}from"node:perf_hooks";import{processWorkspaceInfo as PV}from"@cline/shared";import jL from"simple-git";function g1($){return WL($)}async function z2($){return(await P4($)).info}function V5($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function P4($){let f=g1($),J={rootPath:f,hint:ZL(f)},Q;try{let Z=jL({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});J.associatedRemoteUrls=X}}catch(j){Q??=V5(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=V5(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=V5(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:V5(Z)}}}async function D4($){let f=await z2($);return PV(f)}async function CZ($){let f=FV.now(),J=await P4($),Q=FV.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:PV(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}class L2{manifest;listeners=new Set;constructor($){this.manifest=EZ.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await z2($);return this.manifest=XL(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=g1($),J=this.manifest.workspaces[f];if(J)return this.manifest=EZ.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath(f);return this.manifest=EZ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=g1($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as YL}from"node:crypto";var UV=new Set,zV=new Set;function VL($){return YL("sha256").update($).digest("hex")}function BL($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function LV($){if(!$.telemetry)return;let f=VL($.rootPath),J=$.rootCount??1;if(!UV.has(f))UV.add(f),S6($.telemetry,{root_count:J,vcs_types:BL($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!zV.has(f)){zV.add(f);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",C6($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function AL($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function KL($,f,J){if(f.length>0)for(let W of f)J?.log(W.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(AL).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of $)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function GL($,f){let J=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!J&&!Q)return f;return{...f??{},...J?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function _V($,f){return HL($,f)}function FL($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function PL($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||DL($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function DL($){let f=$?.trim();if(!f)return;let J=_0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function RL($,f,J,Q,Z){let W=J.getProviderSettings($.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...W??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.providerId==="openai-codex"?PL({sessionId:f,configHeaders:$.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:$.apiKey??W?.auth?.accessToken??W?.apiKey}):$.headers??W?.headers,reasoning:GL($,W?.reasoning),modelCatalog:j},V={...d0(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let H=$.fetch??V.fetch??Z;if(H)V.fetch=H;return V}async function OV($){let{input:f,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:B,createSpawnTool:H,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=K$(f.config),{modelCatalogDefaults:P,userInstructionService:F,configExtensions:D,onTeamRestored:_,...O}=A??{},z=Object.keys(O).length>0?O:void 0,{workspaceInfo:U,workspaceMetadata:N,durationMs:y,vcsType:h,initError:u}=await CZ(R),t=z?.extensionContext,f0={...t??{},workspace:{...U,...t?.workspace??{}},session:{...t?.session??{},sessionId:J},logger:t?.logger??z?.logger,telemetry:t?.telemetry??z?.telemetry??Z};LV({telemetry:f0.telemetry,rootPath:U.rootPath,workspaceInfo:U,rootCount:1,vcsType:h,durationMs:y,initError:u,featureFlagEnabled:!0});let o=F2({cwd:f.config.cwd,workspacePath:R,rootSessionId:J,logger:z?.logger,workspaceInfo:U}),$1=VY(z?.hooks)?void 0:G2({rootSessionId:J,workspacePath:R,workspaceInfo:U}),E$=Zf([z?.hooks,$1]),n;if(_V(D,"plugins"))try{n=await H2({pluginPaths:z?.pluginPaths,workspacePath:R,cwd:f.config.cwd,onEvent:Y,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:U,session:f0.session,client:f0.client,user:f0.user,logger:f0.logger,telemetry:f0.telemetry,automation:f0.automation}),KL(n.failures,n.warnings,z?.logger)}catch(If){let l9=If instanceof Error?If.message:String(If);z?.logger?.log?.(`plugin loading failed; continuing without plugins (${l9})`)}let S=nQ(o?[o]:void 0,nQ(z?.extensions,wJ(n?.extensions))),G0=_V(D,"plugins")?$f(n?.pluginPaths??[]):void 0,j0={...f.config,...z??{},sessionId:J,hooks:E$,extensions:S,extensionContext:f0,telemetry:f0.telemetry},w0=RL(j0,J,Q,P,X),bf=Zf([j0.hooks,j0.checkpoint?.enabled===!0?sY({cwd:j0.cwd,sessionId:J,logger:j0.logger,createCheckpoint:j0.checkpoint?.createCheckpoint,initialRunCount:FL(f.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),O1={...j0,providerConfig:w0,workspaceMetadata:N,hooks:bf},X1=f.toolPolicies??j0.toolPolicies??j,j8=U0(W,f.capabilities),kf=j8?.requestToolApproval,N6=j8?.toolExecutors,M1=B?.(O1),q6=new L2({currentWorkspacePath:U.rootPath,workspaces:{[U.rootPath]:U}});return{effectiveInput:f,config:O1,providerConfig:w0,workspaceMetadata:N,workspaceInfo:U,extensions:S,hooks:bf,toolPolicies:X1,requestToolApproval:kf,pluginSandboxShutdown:n?.shutdown,runtimeBuilderInput:{config:O1,hooks:bf,extensions:S,onTeamEvent:V,createSpawnTool:H,onTeamRestored:_,onSubAgentEvent:M1?.onSubAgentEvent,onSubAgentStart:M1?.onSubAgentStart,onSubAgentEnd:M1?.onSubAgentEnd,userInstructionService:F,pluginSkillDirectories:G0,configExtensions:D,toolExecutors:N6,toolPolicies:X1,workspaceManager:q6,logger:O1.logger,telemetry:O1.telemetry,requestToolApproval:kf}}}import{existsSync as H5,mkdirSync as UL,readdirSync as zL,rmdirSync as LL,rmSync as _L,unlinkSync as OL}from"node:fs";import{dirname as MV,join as B5}from"node:path";function e(){return new Date().toISOString()}function R4($){if(!$||!H5($))return;try{OL($)}catch{}}function ML($){let f=Q2($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=i8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class hZ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return B5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!H5(f))UL(f,{recursive:!0});return f}sessionMessagesPath($){return B5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return B5(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!H5(f)){f=MV(f);continue}try{if(zL(f).length>0)break;LL(f)}catch{break}f=MV(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!H5($))return;try{_L($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:Q,fileStem:Z}=ML($),W=this.sessionArtifactsDir(Q);return{messagesPath:B5(W,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as TL}from"@cline/shared/storage";L0();function TV($,f,J,Q,Z){if(J)h6($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else E6($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});NL($.telemetry,{workspacePath:Q})}function NL($,f){let J=TL("Hooks"),Q=F$(f.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[W,j]of Z.entries())d6($,W,j.global,j.workspace)}function NV($,f){for(let J of f.mentions)c6($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)m6($,"file",J.length);for(let J of f.ignoredMentions)v6($,"file","not_found",J)}var qG={};w(qG,{ProviderSettingsManager:()=>L1});import{chmodSync as yG,existsSync as G3,mkdirSync as ME,readFileSync as TE,writeFileSync as NE}from"node:fs";import{basename as SG,dirname as F3}from"node:path";import{resolveProviderSettingsPath as qE}from"@cline/shared/storage";var M={};w(M,{writeHubDiscovery:()=>v5,writeGlobalSettings:()=>x1,withHubStartupLock:()=>c5,verifyHubConnection:()=>G1,updateMcpServerOAuthState:()=>Bf,updateLocalProvider:()=>S9,uninstallPlugin:()=>vW,truncateNotificationBody:()=>F6,toggleDisabledTool:()=>NJ,toTeamProgressLifecycleEvent:()=>v2,toProviderConfig:()=>d0,toHubStatusUrl:()=>U7,toHubHealthUrl:()=>u5,toHookConfigFileName:()=>V4,summarizeUsageFromMessages:()=>W2,stopLocalHubServerGracefully:()=>C7,startLocalOAuthServer:()=>f1,startHubWebSocketServer:()=>Sf,startHubServer:()=>NK,startClineDeviceAuth:()=>o9,splitCoreSessionConfig:()=>v4,spawnDetachedHubServerWithRetry:()=>E2,spawnDetachedHubServer:()=>T7,setTelemetryOptOutGlobally:()=>DY,setMcpServerDisabled:()=>Yf,setDisabledTools:()=>fZ,setDisabledPlugin:()=>OY,setAutoUpdateEnabledGlobally:()=>UY,sendHubCommand:()=>TA,saveProviderOAuthCredentials:()=>I$,saveLocalProviderSettings:()=>nW,saveLocalProviderOAuthCredentials:()=>oW,sanitizeSessionToken:()=>n$,safeParseSettings:()=>X5,safeCreateProviderConfig:()=>SZ,runSubprocessEvent:()=>l2,runHook:()=>r2,reviveTeamStateDates:()=>DJ,restartLocalHubIfIdleAfterStartupTimeout:()=>i5,resolveWorkspaceHubOwnerContext:()=>BH,resolveWorkflowsConfigSearchPaths:()=>y4,resolveSkillsConfigSearchPaths:()=>q4,resolveSharedHubOwnerContext:()=>E0,resolveSessionBackend:()=>t7,resolveRulesConfigSearchPaths:()=>w4,resolveProviderConfig:()=>K4,resolveProviderApiKeyFromSettings:()=>ZQ,resolveProductionHubOwnerContext:()=>n0,resolvePluginSkillDirectoriesFromPaths:()=>$f,resolvePluginConfigSearchPaths:()=>W4,resolveMcpServerRegistrations:()=>A1,resolveLocalClineAuthToken:()=>$3,resolveHubUrl:()=>QW,resolveHubOwnerContext:()=>d1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>m5,resolveHooksConfigSearchPaths:()=>X4,resolveDisabledToolNames:()=>B1,resolveDisabledPluginPaths:()=>$4,resolveDefaultMcpSettingsPath:()=>M0,resolveDefaultHubPort:()=>C2,resolveDefaultHubPathname:()=>M7,resolveDefaultHubHost:()=>O7,resolveCoreSelectedToolIds:()=>UJ,resolveCoreDistinctId:()=>h0,resolveCompatibleLocalHubUrl:()=>$6,resolveClineDir:()=>jH,resolveClineDataDir:()=>Rf,resolveAndLoadAgentPlugins:()=>H2,resolveAgentPluginPaths:()=>e$,requestHubShutdown:()=>e4,requestDesktopToolApproval:()=>EW,rememberRecoverableLocalHubUrl:()=>T$,registerRemoteConfigSessionBlobUpload:()=>R9,registerMcpServersFromSettingsFile:()=>Hf,registerDisposable:()=>zE,refreshProviderModelsFromSource:()=>aW,refreshOpenAICodexToken:()=>t6,refreshOcaToken:()=>fJ,refreshClineToken:()=>a6,readSessionCheckpointHistory:()=>P6,readRemoteConfigSessionBlobUploadMetadata:()=>OW,readHubDiscovery:()=>H0,readGlobalSettings:()=>O0,readBearerToken:()=>A9,probeHubServer:()=>l1,probeHubConnection:()=>MA,prewarmFileIndex:()=>VJ,prewarmDetachedHubServer:()=>l5,prepareRemoteConfigCoreIntegration:()=>TW,parseWorkflowConfigFromMarkdown:()=>N4,parseUserCommandEnvelope:()=>UE,parseSkillConfigFromMarkdown:()=>M4,parseSettings:()=>j5,parseRuleConfigFromMarkdown:()=>T4,parseHookEventPayload:()=>p2,parseConfiguredAgentConfig:()=>Z6,normalizeWorkspacePath:()=>g1,normalizeUserInput:()=>RE,normalizeSdkError:()=>DE,normalizeRuntimeCapabilities:()=>U0,normalizeProviderId:()=>D2,normalizeOAuthProvider:()=>sW,normalizeHubWebSocketUrl:()=>N$,noopBasicLogger:()=>PE,migrateLegacyProviderSettings:()=>O6,mergeRulesForSystemPrompt:()=>N2,mergeAgentHooks:()=>Zf,makeTeamTaskSubSessionId:()=>r8,makeSubSessionId:()=>J2,loginOpenAICodex:()=>A8,loginOcaOAuth:()=>F8,loginLocalProvider:()=>tW,loginClineOAuth:()=>B8,loginAndSaveProviderOAuthCredentials:()=>D8,loginAndSaveLocalProviderOAuthCredentials:()=>eW,loadOpenTelemetryAdapter:()=>JE,loadMcpSettingsFile:()=>Xf,loadLlmsConfigFromFile:()=>H3,loadConfiguredAgentConfigs:()=>x2,loadAgentPluginsFromPathsWithDiagnostics:()=>o$,loadAgentPluginsFromPaths:()=>SJ,loadAgentPluginFromPath:()=>Q4,listSessionHistoryFromBackend:()=>F7,listPluginToolsWithDiagnostics:()=>S5,listPluginTools:()=>g4,listMcpServerOAuthStatuses:()=>I4,listLocalProviders:()=>rW,listHookConfigFiles:()=>F$,isToolDisabledGlobally:()=>zY,isTelemetryOptedOutGlobally:()=>TJ,isSessionNotFoundError:()=>u1,isRuleEnabled:()=>L5,isPluginDisabledGlobally:()=>_Y,isOAuthProvider:()=>k$,isHubReconnectableTransportError:()=>y7,isHubCommandTimeoutError:()=>r5,isDiscoveryFilePresent:()=>YH,isClineAccountActionRequest:()=>A5,isBuiltInProviderId:()=>wZ,isAutoUpdateEnabledGlobally:()=>RY,identifyAccount:()=>y1,hasMcpSettingsFile:()=>v1,getValidOpenAICodexCredentials:()=>K8,getValidOcaCredentials:()=>P8,getValidClineCredentials:()=>H8,getProviderOAuthCredentialsFromSettings:()=>R8,getProviderConfigFields:()=>f3,getProviderConfig:()=>aJ,getProviderAuthStorageId:()=>QQ,getProviderAuthHandler:()=>Q0,getPersistedProviderApiKey:()=>df,getMcpServerOAuthState:()=>Vf,getLocalProviderModels:()=>iW,getLiveModelsCatalog:()=>P2,getFileIndex:()=>h1,getCurrentContextSize:()=>oQ,getCoreHeadlessToolNames:()=>p8,getCoreDefaultEnabledToolIds:()=>RJ,getCoreBuiltinToolCatalog:()=>r$,getCoreAcpToolNames:()=>zJ,getClineDefaultSystemPrompt:()=>ZE,generateWorkspaceInfoWithDiagnostics:()=>P4,generateWorkspaceInfo:()=>z2,formatRulesForSystemPrompt:()=>T2,formatProviderOAuthApiKey:()=>WQ,formatDisplayUserInput:()=>FE,filterExtensionToolRegistrations:()=>wJ,filterDisabledTools:()=>s$,filterDisabledPluginPaths:()=>qJ,fetchClineRecommendedModels:()=>V3,executeClineAccountAction:()=>K5,ensureHubWebSocketServer:()=>K9,ensureHubServer:()=>qK,ensureDetachedHubServer:()=>PH,ensureCustomProvidersLoaded:()=>q9,ensureCompatibleLocalHubUrl:()=>Lf,enrichPromptWithMentions:()=>af,emptyWorkspaceManifest:()=>AE,emptyStoredProviderSettings:()=>U$,discoverPluginModulePaths:()=>j4,deriveSubsessionStatus:()=>n8,deleteLocalProvider:()=>C9,defineLlmsConfig:()=>B3,createWorkflowsConfigDefinition:()=>E4,createUserInstructionConfigService:()=>z$,createToolPoliciesWithPreset:()=>HJ,createTool:()=>HE,createTeamName:()=>L9,createSubprocessHooks:()=>J9,createSpawnAgentTool:()=>H$,createSkillsConfigDefinition:()=>S4,createSessionHost:()=>d2,createRuntimeHost:()=>d2,createRulesConfigDefinition:()=>C4,createRemoteConfigSessionMessagesArtifactUploader:()=>MW,createProviderConfig:()=>yZ,createOpenTelemetryTelemetryService:()=>G6,createOAuthClientCallbacks:()=>_2,createMcpTools:()=>y2,createLocalHubScheduleRuntimeHandlers:()=>G9,createLlmsSdk:()=>K3,createInitialAccumulatedUsage:()=>K0,createInMemoryHubOwnerContext:()=>XH,createHubServerUrl:()=>Z1,createHubAuthToken:()=>g5,createHookConfigFileHooks:()=>B4,createHookConfigFileExtension:()=>F2,createHookAuditHooks:()=>G2,createDisabledMcpToolPolicy:()=>x4,createDisabledMcpToolPolicies:()=>y5,createDelegatedAgentConfigProvider:()=>V$,createDelegatedAgent:()=>B$,createDefaultToolsWithPreset:()=>AJ,createDefaultTools:()=>j$,createDefaultMcpServerClientFactory:()=>w2,createDefaultExecutors:()=>sf,createCoreSettingsService:()=>Kf,createCoreSessionSnapshot:()=>F1,createContributionRegistry:()=>BE,createContextCompactionPrepareTurn:()=>M8,createConfiguredTelemetryService:()=>a1,createConfiguredTelemetryHandle:()=>t2,createConfiguredAgentTools:()=>g2,createClineTelemetryServiceMetadata:()=>VE,createClineTelemetryServiceConfig:()=>YE,createBuiltinTools:()=>i$,createAgentTeamsTools:()=>p$,createAgentRuntime:()=>OE,createAgentHooksExtension:()=>A2,connectToHub:()=>j9,completeClineDeviceAuth:()=>e9,clearPrivateModelsCatalogCache:()=>NZ,clearLiveModelsCatalogCache:()=>TZ,clearHubDiscovery:()=>C0,captureWorkspacePathResolved:()=>h3,captureWorkspaceInitialized:()=>S6,captureWorkspaceInitError:()=>C6,captureToolUsage:()=>I6,captureTokenUsage:()=>b6,captureTaskRestarted:()=>h6,captureTaskCreated:()=>E6,captureTaskCompleted:()=>X8,captureSubagentExecution:()=>V8,captureSkillUsed:()=>x6,captureSdkError:()=>XE,captureProviderConfigured:()=>b3,captureProviderApiError:()=>Y8,captureModeSwitch:()=>k6,captureMentionUsed:()=>m6,captureMentionSearchResults:()=>c6,captureMentionFailed:()=>v6,captureHookDiscovery:()=>d6,captureExtensionActivated:()=>E3,captureDiffEditFailure:()=>g6,captureConversationTurnEvent:()=>xf,captureCompactionSkipped:()=>p6,captureCompactionExecuted:()=>l6,captureAuthSucceeded:()=>q1,captureAuthStarted:()=>N1,captureAuthLoggedOut:()=>o1,captureAuthFailed:()=>w1,captureAgentTeamCreated:()=>u6,captureAgentCreated:()=>e1,buildWorkspaceMetadata:()=>D4,buildTeamProgressSummary:()=>m2,buildSdkErrorProperties:()=>WE,buildRemoteConfigSessionBlobUploadMetadata:()=>P9,buildDelegatedAgentConfig:()=>d$,buildConfiguredAgentToolName:()=>W6,buildConfiguredAgentToolDescriptors:()=>j6,bootstrapAgentTeams:()=>f2,authorizeMcpServerOAuth:()=>N5,addLocalProvider:()=>pW,accumulateUsageTotals:()=>V0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O4,UnifiedConfigFileWatcher:()=>jf,ToolPresets:()=>c0,TelemetryService:()=>a2,TelemetryLoggerSink:()=>K6,TEAM_TOOL_NAMES:()=>$2,SubprocessSandbox:()=>V2,StoredProviderSettingsSchema:()=>U2,StoredProviderSettingsEntrySchema:()=>Y5,SqliteTeamStore:()=>Cf,SqliteSessionStore:()=>D1,SessionVersioningService:()=>S$,SessionVersioningError:()=>k0,SessionSource:()=>P0,SessionNotFoundError:()=>c1,SapSettingsSchema:()=>Q5,SKILLS_CONFIG_DIRECTORY_NAME:()=>_4,SESSION_STATUSES:()=>a8,SESSION_NOT_FOUND_ERROR_CODE:()=>Gf,SDK_ERROR_TELEMETRY_EVENT:()=>LE,RpcClineAccountService:()=>z4,RemoteRuntimeHost:()=>k2,ReasoningSettingsSchema:()=>eJ,RULES_CONFIG_DIRECTORY_NAME:()=>z5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>D9,ProviderSettingsSchema:()=>D$,ProviderSettingsManager:()=>L1,ProviderProtocolSchema:()=>sJ,ProviderIdSchema:()=>F4,ProviderClientSchema:()=>tJ,OpenTelemetryProvider:()=>s2,OcaSettingsSchema:()=>Z5,OPENAI_COMPATIBLE_PROVIDERS:()=>A4,NodeHubClient:()=>W1,NoOpFeatureFlagsProvider:()=>Tf,NativeHubTransportAdapter:()=>z6,ModelCatalogSettingsSchema:()=>W5,LocalRuntimeHost:()=>z1,Llms:()=>QE,InMemoryWorkspaceManager:()=>L2,InMemoryMcpManager:()=>Af,HubUIClient:()=>jW,HubTransportError:()=>T0,HubSessionClient:()=>WW,HubServerTransport:()=>e2,HubScheduleService:()=>n2,HubScheduleCommandService:()=>i2,HubRuntimeHost:()=>p1,HubCommandError:()=>h2,HookEventPayloadSchema:()=>f9,HookEventNameSchema:()=>$9,HookConfigFileName:()=>K2,HOOK_CONFIG_FILE_EVENT_MAP:()=>Y4,HOOKS_CONFIG_DIRECTORY_NAME:()=>xJ,GlobalSettingsSchema:()=>e8,GcpSettingsSchema:()=>f5,FileTeamPersistenceStore:()=>k9,FeatureFlagsService:()=>Mf,FeatureFlagDefaultValue:()=>GE,FEATURE_FLAGS:()=>KE,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>c9,DefaultToolNames:()=>A0,DefaultRuntimeBuilder:()=>J8,DefaultLlmsSdk:()=>M6,DEFAULT_MODELS_CATALOG_URL:()=>pJ,DEFAULT_HUB_PORT:()=>L7,DEFAULT_HUB_PATHNAME:()=>_7,DEFAULT_HUB_HOST:()=>z7,CoreSettingsService:()=>L$,CoreSessionService:()=>U1,ContributionRegistry:()=>jE,ClineCore:()=>H6,ClineAccountService:()=>U4,ChatViewStateSchema:()=>X3,ChatSummarySchema:()=>v9,ChatSessionStatusSchema:()=>x9,ChatSessionConfigSchema:()=>I9,ChatMessageSchema:()=>m9,ChatMessageRoleSchema:()=>g9,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>Y3,BrowserWebSocketHubAdapter:()=>U6,BUILT_IN_PROVIDER_IDS:()=>qZ,BUILT_IN_PROVIDER:()=>G4,AzureSettingsSchema:()=>J5,AwsSettingsSchema:()=>$5,AuthSettingsSchema:()=>oJ,AgentTeamsRuntime:()=>Of,AgentTeam:()=>u2,Agent:()=>_E,ALL_DEFAULT_TOOL_NAMES:()=>Q$});T(M,di);import*as QE from"@cline/llms";import{buildClineSystemPrompt as ZE,buildSdkErrorProperties as WE,ContributionRegistry as jE,captureSdkError as XE,createClineTelemetryServiceConfig as YE,createClineTelemetryServiceMetadata as VE,createContributionRegistry as BE,createTool as HE,emptyWorkspaceManifest as AE,FEATURE_FLAGS as KE,FeatureFlagDefaultValue as GE,formatDisplayUserInput as FE,noopBasicLogger as PE,normalizeSdkError as DE,normalizeUserInput as RE,parseUserCommandEnvelope as UE,registerDisposable as zE,SDK_ERROR_TELEMETRY_EVENT as LE}from"@cline/shared";import"@cline/shared/storage";var wV={};w(wV,{isClineAccountActionRequest:()=>A5,executeClineAccountAction:()=>K5,RpcClineAccountService:()=>z4,ClineAccountService:()=>U4});function qL($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function qV($,f,J){let Q=qL(J);if(Q)return Q;let Z=f.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${W}`}return`Cline account request failed with status ${$}`}class U4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!j.ok)throw Error(qV(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(qV(j.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(W)}}}function A5($){return $.action==="clineAccount"}async function K5($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class z4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var yV={};w(yV,{createOAuthClientCallbacks:()=>_2});function _2($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((Q)=>{$.onOpenUrlError?.({url:f,error:Q})})}catch(Q){$.onOpenUrlError?.({url:f,error:Q})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var FA={};w(FA,{ClineCore:()=>H6});function SV($){if($===!0)return{};if(!$)return;return $}function CV($){if($==="user")return"global";return $}class bZ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function EV($){let{host:f}=$;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:D2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:SL(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:yL(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function G5($){let f=wL($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,W=$.context?.telemetry??$.telemetry;if(!f&&!J&&!Q&&!Z&&!W)return $.context;return{...$.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...f?{automation:f}:{}}}function wL($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function yL($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function SL($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var zB={};w(zB,{createCoreSettingsService:()=>Kf,CoreSettingsService:()=>L$});import{existsSync as C5}from"node:fs";import{basename as DB,isAbsolute as t_,relative as o_}from"node:path";var iV={};w(iV,{resolveWorkflowsConfigSearchPaths:()=>y4,resolveSkillsConfigSearchPaths:()=>q4,resolveRulesConfigSearchPaths:()=>w4,parseWorkflowConfigFromMarkdown:()=>N4,parseSkillConfigFromMarkdown:()=>M4,parseRuleConfigFromMarkdown:()=>T4,createWorkflowsConfigDefinition:()=>E4,createUserInstructionConfigService:()=>z$,createSkillsConfigDefinition:()=>S4,createRulesConfigDefinition:()=>C4,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O4,UnifiedConfigFileWatcher:()=>jf,SKILLS_CONFIG_DIRECTORY_NAME:()=>_4,RULES_CONFIG_DIRECTORY_NAME:()=>z5});import{createHash as CL}from"node:crypto";import{watch as EL}from"node:fs";import{readdir as hL,readFile as bL}from"node:fs/promises";import{join as kL}from"node:path";function IL($){return CL("sha1").update($).digest("hex")}function kV($){return Boolean($&&typeof $==="object"&&"code"in $)}function hV($){return kV($)&&$.code==="ENOENT"}function bV($){return kV($)&&($.code==="EACCES"||$.code==="EPERM")}class jf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=EL(f,()=>{let Q=this.watchedTypesByDirectory.get(f);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:f})})}catch(J){if(!hV(J)&&!bV(J)){let Q=$.get(f);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[Z,W]of Q.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:W.filePath})}for(let[Z,W]of f.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let Q of $.directories){J.add(Q);let Z=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:X}=W;if(J.add(W.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let Y=await bL(X,"utf8"),V={type:$.type,directoryPath:W.directoryPath,fileName:j,filePath:X,content:Y},B=$.parseFile(V),H=$.resolveId(B,V).trim();if(!H)continue;f.set(H,{type:$.type,id:H,item:B,filePath:X,fingerprint:IL(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=$.get(Q);if(Z)Z.add(f);else $.set(Q,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await hL($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:kL($,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch(f){if(hV(f)||bV(f))return[];throw f}}}import{readdir as IZ,readFile as xL,stat as kZ}from"node:fs/promises";import{basename as m1,dirname as gL,extname as P5,join as S0,resolve as L4}from"node:path";import{AGENTS_RULES_FILE_NAME as IV,RULES_CONFIG_DIRECTORY_NAME as z5,resolveGlobalAgentsRulesPath as mL,resolveRulesConfigSearchPaths as vL,resolveSkillsConfigSearchPaths as cL,resolveWorkflowsConfigSearchPaths as uL,SKILLS_CONFIG_DIRECTORY_NAME as _4,WORKFLOWS_CONFIG_DIRECTORY_NAME as O4}from"@cline/shared/storage";import dL from"yaml";var F5="SKILL.md",lL="managed.json",pL=new Set([".md",".markdown",".txt"]);function xZ($){return $.trim().toLowerCase()}function O2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function D5($){return pL.has(P5($).toLowerCase())}function xV($){let f=[],J=new Set;for(let Q of $){let Z=L4(Q);if(J.has(Z))continue;J.add(Z),f.push(Q)}return f}function rL($){let f=[...$?.directories??q4($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...nY({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return xV(f)}async function gZ($){try{let f=await IZ($,{withFileTypes:!0}),J=[];for(let Q of f){if(!Q.isDirectory())continue;let Z=S0($,Q.name),W=S0(Z,lL);try{let j=await xL(W,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(O2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch(f){if(O2(f))return[];throw f}}function mZ($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=dL.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function R5($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let Q=$.trim();if(!Q&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return Q||void 0}function M2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function iL($,f){if(m1($.filePath).toLowerCase()!==IV.toLowerCase())return m1($.filePath,P5($.filePath));if(f&&L4($.filePath)===L4(f,IV))return"Workspace AGENTS.md";if(L4($.filePath)===L4(mL()))return"Global AGENTS.md";return m1($.filePath,P5($.filePath))}function M4($,f){let{data:J,body:Q,parseError:Z}=mZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let X=R5(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:R5(J.description,"description",!1),disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function T4($,f){let{data:J,body:Q,parseError:Z}=mZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=R5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function N4($,f){let{data:J,body:Q,parseError:Z}=mZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=R5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:M2(J.disabled,"disabled")??(M2(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function q4($){return cL($)}function w4($){return vL($)}function y4($){return uL($)}async function gV($){if(m1($)===".cline"){let f=await gZ($);return(await Promise.all(f.map((Q)=>gV(S0(Q,_4))))).flat()}try{let f=await IZ($,{withFileTypes:!0}),J=[];for(let Q of f){if(Q.isFile()&&Q.name===F5){J.push({directoryPath:$,fileName:Q.name,filePath:S0($,Q.name)});continue}let Z=S0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await kZ(Z).then((j)=>j.isDirectory()).catch((j)=>{if(O2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:F5,filePath:S0(Z,F5)})}return J}catch(f){if(O2(f))return[];throw f}}async function U5($){if(m1($)===".cline"){let f=await gZ($);return(await Promise.all(f.map((Q)=>U5(S0(Q,"rules.md"))))).flat()}try{if((await kZ($)).isFile())return[{directoryPath:gL($),fileName:m1($),filePath:$}]}catch(f){if(!O2(f))throw f}try{let J=(await IZ($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&D5(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:S0($,Z.name)})),Q=S0($,"AGENTS.md");try{if((await kZ(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch(f){if(O2(f))return[];throw f}}async function nL($){if(m1($)===".cline"){let f=await gZ($);return(await Promise.all(f.map((Q)=>U5(S0(Q,O4))))).flat()}return U5($)}function S4($){let f=rL($),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?xV([...f,J]):f,discoverFiles:gV,includeFile:(Q)=>Q===F5,parseFile:(Q)=>M4(Q.content,m1(Q.directoryPath)),resolveId:(Q)=>xZ(Q.name)}}function C4($){let f=$?.directories??w4($?.workspacePath),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:U5,includeFile:(Q,Z)=>Q===".clinerules"||D5(Q)||D5(Z),parseFile:(Q)=>T4(Q.content,iL(Q,$?.workspacePath)),resolveId:(Q)=>xZ(Q.name)}}function E4($){let f=$?.directories??y4($?.workspacePath),J=$?.workspacePath?S0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:nL,includeFile:(Q)=>D5(Q),parseFile:(Q)=>N4(Q.content,m1(Q.filePath,P5(Q.filePath))),resolveId:(Q)=>xZ(Q.name)}}function mV($){let f=[S4($?.skills),C4($?.rules),E4($?.workflows)];return new jf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as vV}from"@cline/shared";function aL($,f){if($.description?.trim())return vV($.description,".");if(f==="workflow")return;return vV($.instructions,".")}function sL($){return $.disabled!==!0}function cV($,f){return[...$.getSnapshot(f).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>sL(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:aL(Q.item,f),kind:f})).sort((J,Q)=>J.name.localeCompare(Q.name))}function h4($){let f=new Map;for(let J of[...cV($,"workflow"),...cV($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function uV($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let Q=J[1];if(!Q)return $;let Z=Q.length+1,W=$.slice(Z),j=h4(f).find((X)=>X.name===Q);return j?`${j.instructions}${W}`:$}var lV={};w(lV,{mergeRulesForSystemPrompt:()=>N2,loadRulesForSystemPromptFromWatcher:()=>vZ,listEnabledRulesFromWatcher:()=>dV,isRuleEnabled:()=>L5,formatRulesForSystemPrompt:()=>T2});function L5($){return $.disabled!==!0}function T2($){if($.length===0)return"";return`
|
|
185
193
|
|
|
186
194
|
# Rules
|
|
187
|
-
${
|
|
195
|
+
${$.map((J)=>`## ${J.name}
|
|
188
196
|
${J.instructions}`).join(`
|
|
189
197
|
|
|
190
|
-
`)}`}function
|
|
198
|
+
`)}`}function N2($,f){let J=$?.trim(),Q=f?.trim();if(J&&Q)return`${J}
|
|
191
199
|
|
|
192
|
-
${Q}`;return J||Q||void 0}function
|
|
193
|
-
<command-args>${
|
|
200
|
+
${Q}`;return J||Q||void 0}function dV($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(L5).sort((J,Q)=>J.name.localeCompare(Q.name))}function vZ($){return T2(dV($))}function _5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function tL($){if(!$||$.length===0)return;let f=$.map(_5).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function oL($,f,J){if(!J)return!0;let Q=_5($),Z=_5(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function b4($,f){let J=tL(f);return[...$.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>oL(Z.id,Z.name,J))}function eL($,f){return b4($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function $_($,f,J){let Q=_5(f);if(!Q)return{error:"Missing skill name."};let Z=b4($,J),W=Z.find((B)=>B.id===Q);if(W){let{skill:B}=W;if(B.disabled===!0)return{error:`Skill "${B.name}" is configured but disabled.`};return{id:W.id,skill:B}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=Z.filter(({id:B})=>{if(B===j)return!0;return B.endsWith(`:${j}`)}),Y=X.filter(({skill:B})=>B.disabled!==!0);if(Y.length===1){let{id:B,skill:H}=Y[0];return{id:B,skill:H}}if(Y.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${Y.map(({id:B})=>B).join(", ")}`};if(X.length===1){let{skill:B}=X[0];return{error:`Skill "${B.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:B})=>B).join(", ")}`};let V=eL($,J);return{error:V.length>0?`Skill "${f}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function cZ($,f=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await f;let X=$_($,W,J);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Q.has(Y))return`Skill "${V.name}" is already running.`;Q.add(Y);try{let B=j?.trim(),H=B?`
|
|
201
|
+
<command-args>${B}</command-args>`:"",A=V.description?.trim()?`Description: ${V.description.trim()}
|
|
194
202
|
|
|
195
|
-
`:"";return`<command-name>${
|
|
203
|
+
`:"";return`<command-name>${V.name}</command-name>${H}
|
|
196
204
|
<command-instructions>
|
|
197
|
-
${
|
|
198
|
-
</command-instructions>`}finally{Q.delete(
|
|
205
|
+
${A}${V.instructions}
|
|
206
|
+
</command-instructions>`}finally{Q.delete(Y)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>b4($,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function pV($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await f,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>vZ($.watcher)});if($.registerSkillsTool)Q.registerTool(m$(cZ($.watcher,f,$.allowedSkillNames)));for(let Z of h4($.watcher).filter((W)=>W.kind==="skill"&&$.includeSkills||W.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
|
|
199
207
|
|
|
200
|
-
${j}`:Z.instructions}})}}}class
|
|
201
|
-
${
|
|
208
|
+
${j}`:Z.instructions}})}}}class rV{watcher;ready;stopped=!1;constructor($){this.watcher=mV($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return h4(this.watcher)}resolveRuntimeSlashCommand($){return uV($,this.watcher)}hasConfiguredSkills($){return b4(this.watcher,$).some((f)=>!f.disabled)}createSkillsExecutor($){return cZ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return pV({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function z$($){return new rV($)}import{readFile as f_,writeFile as J_}from"node:fs/promises";import aV from"yaml";function Q_($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J,W=aV.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function nV($,f){return`---
|
|
209
|
+
${aV.stringify($).trimEnd()}
|
|
202
210
|
---
|
|
203
|
-
${
|
|
211
|
+
${f}`}function Z_($,f){let{data:J,body:Q,hadFrontmatter:Z}=Q_($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return nV(J,Q)}return J.disabled=!0,nV(J,Q)}async function sV({filePath:$,enabled:f}){let J=await f_($,"utf8"),Q=Z_(J,f);return await J_($,Q),{filePath:$,enabled:f,disabled:!f}}var GB={};w(GB,{updateMcpServerOAuthState:()=>Bf,setMcpServerDisabled:()=>Yf,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>M0,registerMcpServersFromSettingsFile:()=>Hf,loadMcpSettingsFile:()=>Xf,listMcpServerOAuthStatuses:()=>I4,hasMcpSettingsFile:()=>v1,getMcpServerOAuthState:()=>Vf,createMcpTools:()=>y2,createDisabledMcpToolPolicy:()=>x4,createDisabledMcpToolPolicies:()=>y5,createDefaultMcpServerClientFactory:()=>w2,authorizeMcpServerOAuth:()=>N5,InMemoryMcpManager:()=>Af});import{spawn as C_}from"node:child_process";import{StringDecoder as VB}from"node:string_decoder";import{UnauthorizedError as WB}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as E_}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as L_}from"node:crypto";import{UnauthorizedError as __}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as O_}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as M_}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as T_}from"@modelcontextprotocol/sdk/client/streamableHttp.js";O5();var N_="/mcp/oauth/callback",q_=[1456,1457,1458],w_=300000;function y_($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function S_($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function T5($){let f={};try{f=Vf($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,Q,Z=async(j)=>{let X=q2(j(f))??{};try{f=Bf($.serverName,()=>X,{filePath:$.settingsPath})}catch{f=X}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return S_(f.redirectUrl??$.redirectUrl)},state:()=>{return Q=L_(),Q},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((X)=>({...X,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((X)=>({...X,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((X)=>({...X,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((X)=>{if(j==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((X)=>({...X,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((X)=>({...X,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function M5($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new M_(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new T_(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function ZB($){return new O_({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function N5($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (O5(),QB)),Q=J({filePath:$.filePath}).find((Y)=>Y.name===f);if(!Q)throw Error(`MCP server "${f}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await f1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:q_,callbackPath:$.callbackPath??N_,timeoutMs:$.timeoutMs??w_,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=T5({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await W.resetInteractiveState();let j=ZB($),X;try{let Y=M5({registration:Q,oauthProvider:W.provider,fetch:$.fetch});try{return await j.connect(Y),await j.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(V){if(!(V instanceof __))throw V;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let H=await Z.waitForCallback();if(!H)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(H.error)throw Error(`OAuth authorization failed: ${H.error}`);if(!H.code)throw Error("OAuth callback did not include an authorization code.");let A=W.getLastOAuthState();if(!A)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(H.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(H.code),X=ZB($);let K=M5({registration:Q,oauthProvider:W.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(Y){let V=y_(Y);throw await W.markError(V),Error(V)}finally{await j.close().catch(()=>{return}),await X?.close().catch(()=>{return}),Z.close()}}var h_="2024-11-05",b_=5000,k_=1500,jB="http://127.0.0.1:1456/mcp/oauth/callback";function q5($){return $ instanceof Error?$.message:String($)}function XB($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
|
|
204
212
|
\r
|
|
205
|
-
`,"utf8");return Buffer.concat([J
|
|
206
|
-
`,"utf8")}class
|
|
213
|
+
`,"utf8");return Buffer.concat([J,f])}function YB($){return Buffer.from(`${JSON.stringify($)}
|
|
214
|
+
`,"utf8")}class pZ{buffer="";decoder=new VB("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
|
|
207
215
|
\r
|
|
208
|
-
`);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let W=Number.parseInt(Z[1],10),j=J+4,
|
|
209
|
-
`);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)$.push(Q)}return $}}class kA{registration;process;nextRequestId=1;pending=new Map;framedParser=new zZ;newlineParser=new MZ;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:h_,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},k_),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){$=Q instanceof Error?Q:Error(String(Q))}}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 zZ,this.newlineParser=new MZ,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=S_($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${U5(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch($){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}": ${U5(f)}.${J}`)),$.kill()}async request(f,$,J=b_){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:f,...$?{params:$}:{}},j=new Promise((H,X)=>{let A=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:A})});try{Q.stdin.write(this.protocolMode==="framed"?EA(W):hA(W))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?EA(Q):hA(Q))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}class IA{registration;options;client;authContext;constructor(f,$){this.registration=f;this.options=$}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=G5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??SA});this.authContext=f;try{let $=new E_({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=P5({registration:this.registration,oauthProvider:f.provider,fetch:this.options.fetch});await $.connect(J),await f.clearError(),this.client=$}catch($){let J=$ instanceof CA?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):U5($);throw await f.markError(J),Error(J)}}async disconnect(){let f=this.client;this.client=void 0,await f?.close()}async listTools(){let f=await this.ensureConnectedClient();try{return(await f.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch($){return await this.handleOperationError($)}}async callTool(f){let $=await this.ensureConnectedClient();try{return await $.callTool({name:f.name,arguments:f.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage(f){let $=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!f)return`${$} Run authorizeMcpServerOAuth for this server.`;return`${$} Run authorizeMcpServerOAuth for this server and complete this URL: ${f}`}async handleOperationError(f){let $=this.authContext??G5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??SA}),J=f instanceof CA?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):U5(f);throw await $.markError(J),Error(J)}}function L2(f={}){return($)=>$.transport.type==="stdio"?new kA($):new IA($,f)}K5();function u0(){return Date.now()}function I_(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class B1{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:u0()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=u0(),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=u0(),$)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&&u0()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),Q=await(await this.ensureConnectedClient($)).listTools(),Z=I_(Q);return $.toolCache=Z,$.toolCacheUpdatedAt=u0(),$.updatedAt=u0(),Z})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=u0(),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=u0();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=u0()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=u0(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=u0();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=u0()}}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(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set(f,W),await J.catch(()=>{return});try{return await $()}finally{if(Q?.(),this.operationLocks.get(f)===W)this.operationLocks.delete(f)}}}import{createHash as x_}from"node:crypto";var xA=128,m_=/[^a-zA-Z0-9_-]+/g,mA=8,g_=1,v_="mcp_tool";function c_(f){return x_("sha1").update(f).digest("hex").slice(0,mA)}function u_(f){return f.replace(m_,"_")}var R5=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,Q=u_(J);if(Q===J&&J.length<=xA)return J;let Z=c_(J),W=xA-g_-mA;return`${Q.slice(0,W)||v_}_${Z}`};function qJ(f){return{[(f.nameTransform??R5)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function D5(f){let $={};for(let J of f.toolNames)Object.assign($,qJ({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as d_}from"@cline/shared";function l_(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function _2(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??R5;return $.map((Q)=>{let Z=J({serverName:f.serverName,toolName:Q.name});return d_({name:Z,description:l_(f.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(W,j)=>f.provider.callTool({serverName:f.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}Af();var cA={};q(cA,{listPluginToolsWithDiagnostics:()=>L5,listPluginTools:()=>yJ});import{stat as p_}from"node:fs/promises";Af();var r_=32,O2=new Map;function i_(f,$){if(!O2.has(f)&&O2.size>=r_){let J=O2.keys().next().value;if(J)O2.delete(J)}O2.set(f,$)}async function n_(f){let $=await Promise.all(f.pluginPaths.map(async(J)=>{try{let Q=await p_(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,pathStats:$})}function vA(f,$){return f.map((J)=>({...J,enabled:!$.has(J.name)}))}function a_(f){return f.sort(($,J)=>{let Q=$.name.localeCompare(J.name);if(Q!==0)return Q;return $.path.localeCompare(J.path)})}function t_(f,$){if(!f.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(Q,{workspaceInfo:$}),J}async function L5(f){let $=e$({workspacePath:f.workspacePath,cwd:f.cwd}),J=Xf(f.disabledToolNames);if($.length===0)return{tools:[],failures:[],warnings:[]};let Q=await n_({pluginPaths:$,workspacePath:f.workspacePath,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId}),Z=O2.get(Q);if(Z)return{tools:vA(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],H=[],X;try{X=await O6({pluginPaths:$,cwd:f.cwd,providerId:f.providerId,modelId:f.modelId,workspaceInfo:{rootPath:f.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of t_(V,{rootPath:f.workspacePath}))W.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=$.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let A=a_(W);return i_(Q,{tools:A,failures:j,warnings:H}),{tools:vA(A,J),failures:j,warnings:H}}async function yJ(f){return(await L5(f)).tools}function O5(f,$){if(!$)return"global";let J=o_($,f);return!J.startsWith("..")&&!s_(J)?"workspace":"global"}function wJ(f){return[...f].sort(($,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return Q($.source)-Q(J.source);return $.name.localeCompare(J.name)})}function lA(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function dA(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=lA(f);if(!J)return await $(void 0);let Q=f.cwd?.trim()||J,Z=D$({skills:{workspacePath:J,includePluginSkills:!0,cwd:Q},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await $(Z)}finally{Z.stop()}}function e_(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let Q=J.find((Z)=>Z.id===$.id);if(Q)return Q}for(let Q of J)if(Q.filePath===$.path||Q.item.name===$.name||Q.id===$.name)return Q;return}class L${async list(f={}){return await dA(f,async($)=>{let J=lA(f),Q=[],Z=[],W=[],j=[],H=[];if($){for(let A of $.listRecords("workflow")){let Y=A.item;Q.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"workflow",source:O5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("rule")){let Y=A.item;Z.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"rule",source:O5(A.filePath,J),description:Y.instructions,toggleable:!1})}for(let A of $.listRecords("skill")){let Y=A.item;W.push({id:A.id,name:Y.name,path:A.filePath,enabled:Y.disabled!==!0,kind:"skill",source:O5(A.filePath,J),description:Y.description,toggleable:!0})}}if(J)try{for(let A of await yJ({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))j.push({id:`${A.pluginName}:${A.name}:${A.path}`,name:A.name,path:A.path,enabled:A.enabled,kind:"tool",source:A.source,description:A.description,toggleable:!0})}catch{}let X=z0();if(gf({filePath:X}))try{for(let A of Yf({filePath:X}))H.push({id:A.name,name:A.name,path:X,enabled:A.disabled!==!0,kind:"mcp",source:O5(X,J),description:A.transport.type,toggleable:!0})}catch{}return{workflows:wJ(Q.filter((A)=>_5(A.path))),rules:wJ(Z.filter((A)=>_5(A.path))),skills:wJ(W.filter((A)=>_5(A.path))),tools:wJ(j),mcp:wJ(H.filter((A)=>_5(A.path)))}})}async toggle(f){if(f.type==="skills")return await dA(f,async($)=>{let J=e_($,f),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${f.id??f.name??uA(f.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=f.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??uA(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await _A({filePath:Q,enabled:W}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)F6(f.name);else rH(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}if(f.type==="mcp"){let $=f.name?.trim()||f.id?.trim();if(!$)throw Error("MCP server settings toggle requires a server name.");let J=f.path?.trim()||z0(),Q=f.enabled;if(Q===void 0){let Z=Yf({filePath:J}).find((W)=>W.name===$);if(!Z)throw Error(`Unknown MCP server: ${$}`);Q=Z.disabled===!0}return X1({filePath:J,name:$,disabled:!Q}),{snapshot:await this.list(f),changedTypes:["mcp"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function K1(){return new L$}function rA(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await K1().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await K1().toggle($)}}}function iA(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}var nA={};q(nA,{splitCoreSessionConfig:()=>CJ,isSessionNotFoundError:()=>cf,SessionNotFoundError:()=>vf,SESSION_NOT_FOUND_ERROR_CODE:()=>P1});var P1="session_not_found";class vf extends Error{sessionId;code="session_not_found";constructor(f,$){super($??(f?`session not found: ${f}`:"session not found"));this.sessionId=f;this.name="SessionNotFoundError"}}function cf(f){return f instanceof vf||typeof f==="object"&&f!==null&&"code"in f&&f.code==="session_not_found"}function CJ(f){let{hooks:$,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:Y,...V}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)B.checkpoint=A;if(Y?.compact)B.compaction=Y;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...A?{checkpoint:{enabled:A.enabled}}:{},...Y?{compaction:{enabled:Y.enabled,strategy:Y.strategy,thresholdRatio:Y.thresholdRatio,reserveTokens:Y.reserveTokens,preserveRecentTokens:Y.preserveRecentTokens,maxInputTokens:Y.maxInputTokens,summarizer:Y.summarizer}}:{}},...K?{localRuntime:K}:{}}}function aA(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...fO(f.localRuntime)},localRuntime:f.localRuntime}:f}function NZ(f,$={}){let J=CJ(f.config),Q=D0($.defaultCapabilities,f.capabilities),Z=$O(J.localRuntime,f.localRuntime),W=$.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...f,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function fO(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=f;return W}function $O(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}_0();function tA(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:g.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??F0.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 SJ(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function qZ(f){let $=f?.trim();return $?$:void 0}function JO(f,$){let J=f?.trim();if(!J)return $;let Q=Date.parse(J);if(!Number.isFinite(Q))return $;return new Date(Q).toISOString()}function sA(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function oA(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function QO(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function ZO(f,$){let J=f.eventId.trim(),Q=f.eventType.trim(),Z=f.source.trim(),W=qZ(f.subject),j=qZ(f.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:JO(f.occurredAt,$),workspaceRoot:qZ(f.workspaceRoot),payload:SJ(f.payload)?f.payload:void 0,attributes:SJ(f.attributes)?f.attributes:void 0,dedupeKey:j}}function yZ(f,$){if(!$)return;let J=$.split("."),Q=f;for(let Z of J){if(!SJ(Q))return;Q=Q[Z]}return Q}function WO(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},Q=yZ(J,$);if(Q!==void 0)return Q;if(f.attributes){let Z=yZ(f.attributes,$);if(Z!==void 0)return Z}if(f.payload)return yZ(f.payload,$);return}function T5(f,$){if(Array.isArray($))return $.some((J)=>T5(f,J));if(Array.isArray(f))return f.some((J)=>T5(J,$));if(SJ($)){if(!SJ(f))return!1;return Object.entries($).every(([J,Q])=>T5(f[J],Q))}return Object.is(f,$)}function jO(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,Q])=>T5(WO(f,J),Q))}class wZ{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=ZO(f,$),Q=this.store.insertEventLog(J,{receivedAtIso:$});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],H=[];for(let Y of Z){if(!jO(J,Y.filters)){W.push({specId:Y.specId,externalId:Y.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(Y);let V=this.materializeForSpec(Y,J,Q.record.receivedAt);if(V.run)H.push(V.run);else W.push({specId:Y.specId,externalId:Y.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:W.filter((Y)=>Y.reason!=="filter_mismatch").length});let A=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:A??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec(f,$,J){let Q=$.dedupeKey??$.eventId,Z=f.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:Q});if(X){let A=QO(X.scheduledFor,sA(J,Z)),Y=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:$.eventId,scheduledFor:A});if(Y)return{run:Y,reason:"dedupe_window"}}}let W=f.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:Q,sinceIso:oA(J,W)}))return{reason:"dedupe_window"};let j=f.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:oA(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:Z>0?sA(J,Z):J}),reason:"dedupe_window"}}}class EJ{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 Q of $)if(this.materializeOneOff(Q))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))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 KO}from"node:path";import{buildClineSystemPrompt as PO}from"@cline/shared";import{nowIso as eA}from"@cline/shared/db";import{mkdirSync as HO,writeFileSync as XO}from"node:fs";import{join as AO}from"node:path";import{resolveCronReportsDir as YO}from"@cline/shared/storage";function _$(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function G1(f,$){if($===void 0||$===null)return;return`${f}: ${_$($)}`}function VO(f,$,J){let Q=[`runId: ${_$(f.runId)}`,`specId: ${_$($.specId)}`,`externalId: ${_$($.externalId)}`,`title: ${_$($.title)}`,`triggerKind: ${_$(f.triggerKind)}`,`status: ${_$(f.status)}`,`sourcePath: ${_$($.sourcePath)}`],Z=[G1("sessionId",f.sessionId),G1("startedAt",f.startedAt),G1("completedAt",f.completedAt),G1("triggerEventId",f.triggerEventId),G1("triggerEventType",J?.eventType),G1("triggerEventSource",J?.source),G1("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
|
|
216
|
+
`);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let W=Number.parseInt(Z[1],10),j=J+4,X=j+W;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class rZ{buffer="";decoder=new VB("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
|
|
217
|
+
`);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)f.push(Q)}return f}}class BB{registration;process;nextRequestId=1;pending=new Map;framedParser=new pZ;newlineParser=new rZ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:h_,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},k_),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){f=Q instanceof Error?Q:Error(String(Q))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new pZ,this.newlineParser=new rZ,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=C_(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${q5(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${q5($)}.${J}`)),f.kill()}async request($,f,J=b_){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(Z),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:Y,timeout:V})});try{Q.stdin.write(this.protocolMode==="framed"?XB(W):YB(W))}catch(X){let Y=this.pending.get(Z);if(Y)clearTimeout(Y.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?XB(Q):YB(Q))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class HB{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=T5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??jB});this.authContext=$;try{let f=new E_({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=M5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof WB?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):q5(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??T5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??jB}),J=$ instanceof WB?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):q5($);throw await f.markError(J),Error(J)}}function w2($={}){return(f)=>f.transport.type==="stdio"?new BB(f):new HB(f,$)}O5();function l0(){return Date.now()}function I_($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Af{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:l0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=l0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=l0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&l0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),Q=await(await this.ensureConnectedClient(f)).listTools(),Z=I_(Q);return f.toolCache=Z,f.toolCacheUpdatedAt=l0(),f.updatedAt=l0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=l0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=l0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=l0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=l0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=l0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=l0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,W),await J.catch(()=>{return});try{return await f()}finally{if(Q?.(),this.operationLocks.get($)===W)this.operationLocks.delete($)}}}import{createHash as x_}from"node:crypto";var AB=128,g_=/[^a-zA-Z0-9_-]+/g,KB=8,m_=1,v_="mcp_tool";function c_($){return x_("sha1").update($).digest("hex").slice(0,KB)}function u_($){return $.replace(g_,"_")}var w5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,Q=u_(J);if(Q===J&&J.length<=AB)return J;let Z=c_(J),W=AB-m_-KB;return`${Q.slice(0,W)||v_}_${Z}`};function x4($){return{[($.nameTransform??w5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function y5($){let f={};for(let J of $.toolNames)Object.assign(f,x4({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as d_}from"@cline/shared";function l_($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function y2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??w5;return f.map((Q)=>{let Z=J({serverName:$.serverName,toolName:Q.name});return d_({name:Z,description:l_($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(W,j)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}H1();var PB={};w(PB,{listPluginToolsWithDiagnostics:()=>S5,listPluginTools:()=>g4});import{stat as p_}from"node:fs/promises";H1();var r_=32,S2=new Map;function i_($,f){if(!S2.has($)&&S2.size>=r_){let J=S2.keys().next().value;if(J)S2.delete(J)}S2.set($,f)}async function n_($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let Q=await p_(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function FB($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function a_($){return $.sort((f,J)=>{let Q=f.name.localeCompare(J.name);if(Q!==0)return Q;return f.path.localeCompare(J.path)})}function s_($,f){if(!$.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(Q,{workspaceInfo:f}),J}async function S5($){let f=e$({workspacePath:$.workspacePath,cwd:$.cwd}),J=B1($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let Q=await n_({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=S2.get(Q);if(Z)return{tools:FB(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],X=[],Y;try{Y=await EJ({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let A=H.__clinePluginPath;if(!A)continue;for(let K of s_(H,{rootPath:$.workspacePath}))W.push({name:K.name,pluginName:H.name,path:A,source:A.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(H){j=f.map((A)=>({pluginPath:A,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=a_(W);return i_(Q,{tools:V,failures:j,warnings:X}),{tools:FB(V,J),failures:j,warnings:X}}async function g4($){return(await S5($)).tools}function E5($,f){if(!f)return"global";let J=o_(f,$);return!J.startsWith("..")&&!t_(J)?"workspace":"global"}function m4($){return[...$].sort((f,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return Q(f.source)-Q(J.source);return f.name.localeCompare(J.name)})}function UB($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function RB($,f){if($.userInstructionService)return await f($.userInstructionService);let J=UB($);if(!J)return await f(void 0);let Q=$.cwd?.trim()||J,Z=z$({skills:{workspacePath:J,includePluginSkills:!0,cwd:Q},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function e_($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let Q=J.find((Z)=>Z.id===f.id);if(Q)return Q}for(let Q of J)if(Q.filePath===f.path||Q.item.name===f.name||Q.id===f.name)return Q;return}class L${async list($={}){return await RB($,async(f)=>{let J=UB($),Q=[],Z=[],W=[],j=[],X=[];if(f){for(let V of f.listRecords("workflow")){let B=V.item;Q.push({id:V.id,name:B.name,path:V.filePath,enabled:B.disabled!==!0,kind:"workflow",source:E5(V.filePath,J),description:B.instructions,toggleable:!1})}for(let V of f.listRecords("rule")){let B=V.item;Z.push({id:V.id,name:B.name,path:V.filePath,enabled:B.disabled!==!0,kind:"rule",source:E5(V.filePath,J),description:B.instructions,toggleable:!1})}for(let V of f.listRecords("skill")){let B=V.item;W.push({id:V.id,name:B.name,path:V.filePath,enabled:B.disabled!==!0,kind:"skill",source:E5(V.filePath,J),description:B.description,toggleable:!0})}}if(J)try{for(let V of await g4({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=M0();if(v1({filePath:Y}))try{for(let V of A1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:E5(Y,J),description:V.transport.type,toggleable:!0})}catch{}return{workflows:m4(Q.filter((V)=>C5(V.path))),rules:m4(Z.filter((V)=>C5(V.path))),skills:m4(W.filter((V)=>C5(V.path))),tools:m4(j),mcp:m4(X.filter((V)=>C5(V.path)))}})}async toggle($){if($.type==="skills")return await RB($,async(f)=>{let J=e_(f,$),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??DB($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=$.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??DB($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await sV({filePath:Q,enabled:W}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)NJ($.name);else LY($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||M0(),Q=$.enabled;if(Q===void 0){let Z=A1({filePath:J}).find((W)=>W.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);Q=Z.disabled===!0}return Yf({filePath:J,name:f,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Kf(){return new L$}function LB($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Kf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Kf().toggle(f)}}}function _B($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}var OB={};w(OB,{splitCoreSessionConfig:()=>v4,isSessionNotFoundError:()=>u1,SessionNotFoundError:()=>c1,SESSION_NOT_FOUND_ERROR_CODE:()=>Gf});var Gf="session_not_found";class c1 extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function u1($){return $ instanceof c1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function v4($){let{hooks:f,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:B,...H}=$,A={};if(f)A.hooks=f;if(J)A.logger=J;if(Q)A.telemetry=Q;if(Z)A.extensionContext=Z;if(W)A.extraTools=W;if(j)A.extensions=j;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(B?.compact)A.compaction=B;let K=Object.keys(A).length>0?A:void 0;return{config:{...H,...V?{checkpoint:{enabled:V.enabled}}:{},...B?{compaction:{enabled:B.enabled,strategy:B.strategy,thresholdRatio:B.thresholdRatio,reserveTokens:B.reserveTokens,preserveRecentTokens:B.preserveRecentTokens,maxInputTokens:B.maxInputTokens,summarizer:B.summarizer}}:{}},...K?{localRuntime:K}:{}}}function MB($){let f=$.config;return"providerId"in f?{...$,config:{...f,...$O($.localRuntime)},localRuntime:$.localRuntime}:$}function iZ($,f={}){let J=v4($.config),Q=U0(f.defaultCapabilities,$.capabilities),Z=fO(J.localRuntime,$.localRuntime),W=f.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...$,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function $O($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=$;return W}function fO(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function TB($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??P0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function c4($){return!!$&&typeof $==="object"&&!Array.isArray($)}function nZ($){let f=$?.trim();return f?f:void 0}function JO($,f){let J=$?.trim();if(!J)return f;let Q=Date.parse(J);if(!Number.isFinite(Q))return f;return new Date(Q).toISOString()}function NB($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function qB($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function QO($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function ZO($,f){let J=$.eventId.trim(),Q=$.eventType.trim(),Z=$.source.trim(),W=nZ($.subject),j=nZ($.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:JO($.occurredAt,f),workspaceRoot:nZ($.workspaceRoot),payload:c4($.payload)?$.payload:void 0,attributes:c4($.attributes)?$.attributes:void 0,dedupeKey:j}}function aZ($,f){if(!f)return;let J=f.split("."),Q=$;for(let Z of J){if(!c4(Q))return;Q=Q[Z]}return Q}function WO($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=aZ(J,f);if(Q!==void 0)return Q;if($.attributes){let Z=aZ($.attributes,f);if(Z!==void 0)return Z}if($.payload)return aZ($.payload,f);return}function h5($,f){if(Array.isArray(f))return f.some((J)=>h5($,J));if(Array.isArray($))return $.some((J)=>h5(J,f));if(c4(f)){if(!c4($))return!1;return Object.entries(f).every(([J,Q])=>h5($[J],Q))}return Object.is($,f)}function jO($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,Q])=>h5(WO($,J),Q))}class sZ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=ZO($,f),Q=this.store.insertEventLog(J,{receivedAtIso:f});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],X=[];for(let B of Z){if(!jO(J,B.filters)){W.push({specId:B.specId,externalId:B.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(B);let H=this.materializeForSpec(B,J,Q.record.receivedAt);if(H.run)X.push(H.run);else W.push({specId:B.specId,externalId:B.externalId,reason:H.reason,dedupeKey:J.dedupeKey})}let Y=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:Y,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:W.filter((B)=>B.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:Y,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:V??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let Q=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(Y){let V=QO(Y.scheduledFor,NB(J,Z)),B=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:f.eventId,scheduledFor:V});if(B)return{run:B,reason:"dedupe_window"}}}let W=$.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:qB(J,W)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:qB(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?NB(J,Z):J}),reason:"dedupe_window"}}}class u4{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of f)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as KO}from"node:path";import{buildClineSystemPrompt as GO}from"@cline/shared";import{nowIso as wB}from"@cline/shared/db";import{mkdirSync as XO,writeFileSync as YO}from"node:fs";import{join as VO}from"node:path";import{resolveCronReportsDir as BO}from"@cline/shared/storage";function _$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Ff($,f){if(f===void 0||f===null)return;return`${$}: ${_$(f)}`}function HO($,f,J){let Q=[`runId: ${_$($.runId)}`,`specId: ${_$(f.specId)}`,`externalId: ${_$(f.externalId)}`,`title: ${_$(f.title)}`,`triggerKind: ${_$($.triggerKind)}`,`status: ${_$($.status)}`,`sourcePath: ${_$(f.sourcePath)}`],Z=[Ff("sessionId",$.sessionId),Ff("startedAt",$.startedAt),Ff("completedAt",$.completedAt),Ff("triggerEventId",$.triggerEventId),Ff("triggerEventType",J?.eventType),Ff("triggerEventSource",J?.source),Ff("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
|
|
210
218
|
${Q.join(`
|
|
211
219
|
`)}
|
|
212
220
|
---
|
|
213
|
-
`}function
|
|
221
|
+
`}function AO($){let f=[];if($.triggerEvent){let J=$.triggerEvent,Q=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
|
|
214
222
|
|
|
215
223
|
${Q.join(`
|
|
216
224
|
`)}
|
|
217
|
-
`)}if(f.
|
|
225
|
+
`)}if($.error)f.push(`## Error
|
|
218
226
|
|
|
219
|
-
${
|
|
220
|
-
`);if(
|
|
227
|
+
${$.error}
|
|
228
|
+
`);if($.finalText&&$.finalText.trim().length>0)f.push(`## Summary
|
|
221
229
|
|
|
222
|
-
${
|
|
223
|
-
`);if(
|
|
230
|
+
${$.finalText.trim()}
|
|
231
|
+
`);if($.usage){let J=$.usage,Q=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((Z)=>Z.length>0);if(Q.length>0)f.push(`## Usage
|
|
224
232
|
|
|
225
233
|
${Q.join(`
|
|
226
234
|
`)}
|
|
227
|
-
`)}if(
|
|
235
|
+
`)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((Q)=>{let Z=[`- ${Q.name}`];if(Q.durationMs!==void 0)Z.push(`(${Q.durationMs}ms)`);if(Q.error)Z.push(`error: ${Q.error}`);return Z.join(" ")});f.push(`## Tool Calls
|
|
228
236
|
|
|
229
237
|
${J.join(`
|
|
230
238
|
`)}
|
|
231
|
-
`)}return
|
|
232
|
-
`)}function
|
|
233
|
-
${
|
|
234
|
-
`)}class
|
|
239
|
+
`)}return f.join(`
|
|
240
|
+
`)}function tZ($){let f=BO($.specs);XO(f,{recursive:!0});let J=VO(f,`${$.run.runId}.md`),Q=`${HO($.run,$.spec,$.data.triggerEvent)}
|
|
241
|
+
${AO($.data)}`;return YO(J,Q,"utf8"),J}class oZ{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=Q)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var FO=15000,PO=90,yB=["rules","skills","plugins"];function DO($,f){return new Set($.extensions??yB).has(f)}function RO($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)J[Q]={enabled:!0,autoApprove:!0};if(f==="yolo")J[A0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function UO($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
|
|
242
|
+
`)}class eZ extends Error{constructor($){super($);this.name="TimeoutError"}}async function zO($,f){if(f<=0)return $;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new eZ("cron run timed out"))},f)});try{return await Promise.race([$,Q])}finally{if(J)clearTimeout(J)}}class d4{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new oZ($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??PO)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let $=Math.max(2000,this.options.pollIntervalMs??FO);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:wB(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,Q)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let W=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,Y=Date.now(),V;if(J.timeoutSeconds&&J.timeoutSeconds>0)V=Y+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let B=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(B)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let A={config:B,prompt:this.buildPrompt(J,W)},K=this.options.runtimeHandlers.sendSession(j,A),G=V?Math.max(1,V-Date.now()):0,P=(await zO(K,G)).result,F=Date.now(),D=tZ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:F-Y,triggerEvent:W}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:D,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,wB())}catch(B){let H=B instanceof eZ;if(j&&H)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let A=B instanceof Error?B.message:String(B),K=Date.now(),G=tZ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:A,durationMs:K-Y,triggerEvent:W}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(J);if(!Q)return;let Z=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:Z,errorMessage:Q.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let Q={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
|
|
235
243
|
|
|
236
244
|
Trigger event:
|
|
237
|
-
${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(
|
|
238
|
-
`);if(
|
|
239
|
-
`))return{frontmatter:void 0,body
|
|
240
|
-
---`);if(Q===-1)return{frontmatter:void 0,body
|
|
241
|
-
`))W=W.slice(1);return{frontmatter:Z,body:W}}function
|
|
242
|
-
`),J.update(
|
|
245
|
+
${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,Q){let Z=UO($.notesDirectory),W=N2(void 0,Z),j=await D4(f),X=GO({ide:"Cline Cron",workspaceRoot:f,workspaceName:KO(f),metadata:j,rules:$.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?N2(X,W)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),Q=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,W=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:W,provider:J,model:Q,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:RO($,j),configExtensions:yB.filter((X)=>DO($,X))}}}import{existsSync as dO,readdirSync as lO,readFileSync as pO,statSync as rO}from"node:fs";import{relative as iO}from"node:path";import{resolveCronSpecsDir as nO}from"@cline/shared/storage";function l4($,f,J,Q){let Z=new Set;function W(j){let X=j.toLowerCase();if(Q){let V=Q.indexOf(X);if(V!==-1)return V+f}let Y=Number(j);if(!Number.isInteger(Y)||Y<f||Y>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return Y}for(let j of $.split(",")){if(j==="*"){for(let V=f;V<=J;V+=1)Z.add(V);continue}let X=j.indexOf("/");if(X!==-1){let V=j.slice(0,X),B=Number(j.slice(X+1));if(!Number.isInteger(B)||B<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let H=f,A=J;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)H=W(V.slice(0,K)),A=W(V.slice(K+1));else H=W(V)}if(H>A)throw Error(`Invalid cron range "${V}"`);for(let K=H;K<=A;K+=B)Z.add(K);continue}let Y=j.indexOf("-");if(Y!==-1){let V=W(j.slice(0,Y)),B=W(j.slice(Y+1));if(V>B)throw Error(`Invalid cron range "${j}"`);for(let H=V;H<=B;H+=1)Z.add(H);continue}Z.add(W(j))}return[...Z].sort((j,X)=>j-X)}var LO=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],CB=["sun","mon","tue","wed","thu","fri","sat"];function p4($,f,J){let Q=$[f];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return Q}function $7($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function f7($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:l4(p4(f,0,$),0,59),hours:l4(p4(f,1,$),0,23),daysOfMonth:l4(p4(f,2,$),1,31),months:l4(p4(f,3,$),1,12,LO),daysOfWeek:l4(p4(f,4,$),0,6,CB)}}function J7($){f7($)}function EB($,f,J=Date.now()){Pf($,J,f)}var SB=new Map,_O=new Map(CB.map(($,f)=>[$,f]));function hB($){let f=$?.trim();return f?f:void 0}function bB($){let f=SB.get($);if(f)return f;let J=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return SB.set($,J),J}function OO($){let f=hB($);if(!f)return;bB(f).format(new Date)}function MO($,f){let J=bB(f).formatToParts(new Date($)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=_O.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function TO($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function NO($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function qO($,f,J){let Q=f7($),Z=new Date(f);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(W<=X){if(NO(Q,MO(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function Pf($,f,J){let Q=hB(J);if(Q)return OO(Q),qO($,f,Q);let Z=f7($),W=new Date(f);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:B,minute:H}=TO(W.getTime());if(!Z.months.includes(X)){let A=Z.months.find((G)=>G>X)??$7(Z.months,"months"),K=A<=X?1:0;W=new Date(W.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(Y)||!Z.daysOfWeek.includes(V)){W=new Date(W.getFullYear(),W.getMonth(),Y+1,0,0,0,0);continue}if(!Z.hours.includes(B)){let A=Z.hours.find((G)=>G>B)??$7(Z.hours,"hours"),K=A<=B?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+K,A,0,0,0);continue}if(!Z.minutes.includes(H)){let A=Z.minutes.find((G)=>G>H)??$7(Z.minutes,"minutes"),K=A<=H?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate(),W.getHours()+K,A,0,0);continue}return W.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as wO}from"node:crypto";import yO from"yaml";function SO($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function CO($){let f=$.replace(/\r\n/g,`
|
|
246
|
+
`);if(!f.startsWith(`---
|
|
247
|
+
`))return{frontmatter:void 0,body:$};let J=f.slice(4),Q=J.indexOf(`
|
|
248
|
+
---`);if(Q===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,Q),W=J.slice(Q+4);if(W.startsWith(`
|
|
249
|
+
`))W=W.slice(1);return{frontmatter:Z,body:W}}function p0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function EO($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function W7($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function hO($){let f=W7($);if(!f)return;let J=p0(f.providerId),Q=p0(f.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function bO($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function IB($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let Q=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var kO=new Set(Q$);function IO($){let f=IB($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!kO.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var xO=new Set(["rules","skills","plugins"]);function gO($){let f=IB($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!xO.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function Q7($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function Z7($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function j7($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>j7(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${f.map(([J,Q])=>`${JSON.stringify(J)}:${j7(Q)}`).join(",")}}`}function xB($,f){let J=wO("sha256");return J.update(j7($)),J.update(`
|
|
250
|
+
`),J.update(f),J.digest("hex")}function mO($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var vO=["schedule","timezone"],cO=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],uO=["cwd"];function kB($,f,J,Q,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:xB(Q,J),error:Z}}function K1($,f,J,Q,Z,W){return{externalId:$,relativePath:f,triggerKind:J,body:Q,contentHash:Z,error:W}}function gB($){let f=$.relativePath.replace(/\\/g,"/"),J=SO(f),{frontmatter:Q,body:Z}=CO($.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let D=yO.parse(Q);if(D&&typeof D==="object"&&!Array.isArray(D))W=D;else if(D!==null&&D!==void 0)return kB(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(D){return kB(f,J,Z,{},D instanceof Error?`failed to parse frontmatter: ${D.message}`:"failed to parse frontmatter")}let j=xB(W,Z),X=p0(W.id),Y=X??f;if(J!=="schedule"){for(let D of vO)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is only allowed on *.cron.md specs`)}for(let D of uO)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let D of cO)if(W[D]!==void 0)return K1(Y,f,J,Z,j,`field "${D}" is only allowed on .event.md specs`)}let V=p0(W.prompt),B=Z.trim(),H=V??(B.length>0?B:void 0);if(!H)return K1(Y,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let A=p0(W.workspaceRoot);if(!A)return K1(Y,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=IO(W.tools),G=gO(W.extensions)}catch(D){return K1(Y,f,J,Z,j,D instanceof Error?D.message:String(D))}let R=bO(W.mode);if(W.mode!==void 0&&R===void 0)return K1(Y,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:X,title:p0(W.title)??X??mO(f),prompt:H,workspaceRoot:A,mode:R??"yolo",systemPrompt:p0(W.systemPrompt),modelSelection:hO(W.modelSelection),maxIterations:Q7(W.maxIterations),timeoutSeconds:Q7(W.timeoutSeconds),tools:K,notesDirectory:p0(W.notesDirectory),extensions:G,source:p0(W.source)??"user",tags:EO(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:W7(W.metadata)},F;if(J==="schedule"){let D=p0(W.schedule);if(!D)return K1(Y,f,J,Z,j,"schedule is required for *.cron.md specs");let _=p0(W.timezone);try{EB(D,_)}catch(z){return K1(Y,f,J,Z,j,z instanceof Error?z.message:String(z))}F={...P,triggerKind:"schedule",schedule:D,timezone:_}}else if(J==="event"){let D=p0(W.event);if(!D)return K1(Y,f,J,Z,j,"event is required for .event.md specs");F={...P,triggerKind:"event",event:D,filters:W7(W.filters),debounceSeconds:Z7(W.debounceSeconds),dedupeWindowSeconds:Z7(W.dedupeWindowSeconds),cooldownSeconds:Z7(W.cooldownSeconds),maxParallel:Q7(W.maxParallel)}}else F={...P,triggerKind:"one_off"};return{externalId:Y,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:F}}function aO($,f){return iO($,f).replace(/\\/g,"/")}function sO($){if(!dO($))return[];let f=[],J=[$];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=lO(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;f.push(j)}}return f}class X7{store;cronDir;constructor($){this.store=$.store,this.cronDir=nO($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=sO(this.cronDir),J=new Set;for(let Z of f){let W=aO(this.cronDir,Z);J.add(W),$.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),Q,Z;try{Q=pO(f,"utf8"),Z=rO(f).mtimeMs}catch{return}let j=gB({relativePath:$,raw:Q}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),Q=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=Pf($.scheduleExpr,Q,$.timezone),W=new Date(Z).toISOString();if($.nextRunAt!==W)this.store.updateSpecNextRunAt($.specId,W)}catch{}}}import{existsSync as tO,mkdirSync as oO,watch as eO}from"node:fs";import{relative as $M,resolve as fM}from"node:path";var JM=250;class Y7{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??JM),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{oO($,{recursive:!0}),this.watcher=eO($,{recursive:!0},(f,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=fM(this.reconciler.getCronDir(),$);if(!tO(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=$M(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as r4}from"node:crypto";import{asOptionalString as g,asString as s,loadSqliteDb as ZM,nowIso as z0}from"@cline/shared/db";import{resolveCronDbPath as WM}from"@cline/shared/storage";var QM=[`CREATE TABLE IF NOT EXISTS cron_specs (
|
|
243
251
|
spec_id TEXT PRIMARY KEY,
|
|
244
252
|
external_id TEXT NOT NULL,
|
|
245
253
|
source_path TEXT NOT NULL UNIQUE,
|
|
@@ -330,17 +338,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
330
338
|
ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
|
|
331
339
|
ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
|
|
332
340
|
ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
|
|
333
|
-
ON cron_specs(source_path);`];function
|
|
341
|
+
ON cron_specs(source_path);`];function mB($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of QM)$.exec(f)}function b5($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function V7($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function Df($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function O$($){return{specId:s($.spec_id),externalId:s($.external_id),sourcePath:s($.source_path),triggerKind:s($.trigger_kind),sourceMtimeMs:Df($.source_mtime_ms),sourceHash:g($.source_hash),parseStatus:s($.parse_status)==="invalid"?"invalid":"valid",parseError:g($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:s($.title),prompt:g($.prompt),workspaceRoot:g($.workspace_root),scheduleExpr:g($.schedule_expr),timezone:g($.timezone),eventType:g($.event_type),filters:b5(g($.filters_json)),debounceSeconds:Df($.debounce_seconds),dedupeWindowSeconds:Df($.dedupe_window_seconds),cooldownSeconds:Df($.cooldown_seconds),mode:g($.mode),systemPrompt:g($.system_prompt),providerId:g($.provider_id),modelId:g($.model_id),maxIterations:Df($.max_iterations),timeoutSeconds:Df($.timeout_seconds),maxParallel:Df($.max_parallel),tools:V7(g($.tools_json),{preserveEmpty:!0}),notesDirectory:g($.notes_directory),extensions:V7(g($.extensions_json),{preserveEmpty:!0}),source:g($.source),tags:V7(g($.tags_json)),metadata:b5(g($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:g($.last_materialized_run_id),lastRunAt:g($.last_run_at),nextRunAt:g($.next_run_at),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function B7($){return{runId:s($.run_id),specId:s($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:s($.trigger_kind),status:s($.status),claimToken:g($.claim_token),claimStartedAt:g($.claim_started_at),claimUntilAt:g($.claim_until_at),scheduledFor:g($.scheduled_for),triggerEventId:g($.trigger_event_id),startedAt:g($.started_at),completedAt:g($.completed_at),sessionId:g($.session_id),reportPath:g($.report_path),error:g($.error),attemptCount:Number($.attempt_count??0),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function vB($){return{eventId:s($.event_id),eventType:s($.event_type),source:s($.source),subject:g($.subject),occurredAt:s($.occurred_at),receivedAt:s($.received_at),workspaceRoot:g($.workspace_root),dedupeKey:g($.dedupe_key),payload:b5(g($.payload_json)),attributes:b5(g($.attributes_json)),processingStatus:s($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:g($.error),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function cB($){return $?JSON.stringify($):null}var jM=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function uB($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function XM($,f,J,Q){for(let Z of jM){let W=$[Z],j=f[Z];if(uB(W)!==uB(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function YM($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function VM($){return`hub/schedules/${$}.cron.md`}function BM($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function H7($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:BM($)}}function dB($){return JSON.stringify(H7($))}function HM($,f){let J=$.metadata?{...$.metadata}:{},Q=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:Q,tags:f.tags??$.tags,runtimeOptions:W,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class i4{db;constructor($={}){let f=$.dbPath??WM();this.db=ZM(f),mB(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?O$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?O$(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?O$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>O$(j))}createHubSchedule($){let f=`sched_${r4()}`,J=this.upsertSpec({externalId:f,sourcePath:VM(f),triggerKind:"schedule",sourceHash:dB($),parseStatus:"valid",spec:H7($)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
|
|
334
342
|
WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
|
|
335
|
-
ORDER BY created_at ASC LIMIT 1`).get(
|
|
336
|
-
WHERE ${
|
|
337
|
-
ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>O$(W))}updateHubSchedule(f
|
|
343
|
+
ORDER BY created_at ASC LIMIT 1`).get($);return f?O$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let W of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
|
|
344
|
+
WHERE ${f.join(" AND ")}
|
|
345
|
+
ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>O$(W))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let Q=HM(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:dB(Q),parseStatus:"valid",spec:H7(Q)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:z0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
|
|
338
346
|
WHERE trigger_kind = 'event'
|
|
339
347
|
AND event_type = ?
|
|
340
348
|
AND enabled = 1
|
|
341
349
|
AND removed = 0
|
|
342
350
|
AND parse_status = 'valid'
|
|
343
|
-
ORDER BY created_at ASC`).all(
|
|
351
|
+
ORDER BY created_at ASC`).all($).map((J)=>O$(J))}upsertSpec($){let f=z0(),J=this.getSpecBySourcePath($.sourcePath),Q=$.spec,Z={title:Q?.title??J?.title??YM($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},W=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let B=`cspec_${r4()}`;this.insertSpecRow(B,$,Z,W,f);let H=this.getSpec(B);if(!H)throw Error("failed to insert cron_spec row");return{record:H,created:!0,revisionChanged:!0}}let X=J.sourceHash!==$.sourceHash&&XM(J,Z,J.enabled,W),Y=X?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,W,Y,f);let V=this.getSpec(J.specId);if(!V)throw Error("failed to reload cron_spec after update");return{record:V,created:!1,revisionChanged:X}}insertSpecRow($,f,J,Q,Z){let W=f.spec;this.db.prepare(`INSERT INTO cron_specs (
|
|
344
352
|
spec_id, external_id, source_path, trigger_kind,
|
|
345
353
|
source_mtime_ms, source_hash, parse_status, parse_error,
|
|
346
354
|
enabled, removed, title, prompt, workspace_root,
|
|
@@ -351,7 +359,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
351
359
|
tools_json, notes_directory, extensions_json, source,
|
|
352
360
|
tags_json, metadata_json, revision,
|
|
353
361
|
created_at, updated_at
|
|
354
|
-
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f
|
|
362
|
+
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,f.externalId,f.sourcePath,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?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,W?.tags?JSON.stringify(W.tags):null,W?.metadata?JSON.stringify(W.metadata):null,1,Z,Z)}updateSpecRow($,f,J,Q,Z,W){let j=f.spec;this.db.prepare(`UPDATE cron_specs SET
|
|
355
363
|
external_id = ?, trigger_kind = ?,
|
|
356
364
|
source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
|
|
357
365
|
enabled = ?, removed = 0, title = ?, prompt = ?,
|
|
@@ -363,7 +371,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
363
371
|
tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
|
|
364
372
|
tags_json = ?, metadata_json = ?,
|
|
365
373
|
revision = ?, updated_at = ?
|
|
366
|
-
WHERE spec_id = ?`).run(
|
|
374
|
+
WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,W,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(z0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,z0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,z0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,z0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(Pf(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=O$(Q);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let W=Z.nextRunAt;if(!W){let Y=new Date(Pf(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Y,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Y}}if(new Date(W).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${r4()}`,X;try{X=new Date(Pf(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{X=void 0}return this.db.prepare(`INSERT INTO cron_runs (
|
|
367
375
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
368
376
|
scheduled_for, trigger_event_id, attempt_count,
|
|
369
377
|
created_at, updated_at
|
|
@@ -372,54 +380,54 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
372
380
|
last_run_at = ?,
|
|
373
381
|
next_run_at = ?,
|
|
374
382
|
updated_at = ?
|
|
375
|
-
WHERE spec_id = ?`).run(j,J,
|
|
383
|
+
WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?B7(f):void 0}insertEventLog($,f={}){let J=z0(),Q=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=$.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||Q,Y=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
|
|
376
384
|
event_id, event_type, source, subject,
|
|
377
385
|
occurred_at, received_at, workspace_root, dedupe_key,
|
|
378
386
|
payload_json, attributes_json, processing_status,
|
|
379
387
|
matched_spec_count, queued_run_count, suppressed_count,
|
|
380
388
|
error, created_at, updated_at
|
|
381
|
-
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j
|
|
389
|
+
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,$.subject?.trim()||null,X,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,cB($.payload),cB($.attributes),"received",0,0,0,null,J,J).changes??0,V=this.getEventLog(Z);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?vB(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
|
|
382
390
|
ORDER BY received_at DESC, created_at DESC
|
|
383
|
-
LIMIT ?`).all(...J,Z).map((j)=>
|
|
391
|
+
LIMIT ?`).all(...J,Z).map((j)=>vB(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
|
|
384
392
|
processing_status = ?,
|
|
385
393
|
matched_spec_count = COALESCE(?, matched_spec_count),
|
|
386
394
|
queued_run_count = COALESCE(?, queued_run_count),
|
|
387
395
|
suppressed_count = COALESCE(?, suppressed_count),
|
|
388
396
|
error = ?,
|
|
389
397
|
updated_at = ?
|
|
390
|
-
WHERE event_id = ?`).run(
|
|
398
|
+
WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,z0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let Y of j)J.push(Y)}}let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>B7(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
|
|
391
399
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
392
400
|
WHERE r.spec_id = ?
|
|
393
401
|
AND r.trigger_kind = 'event'
|
|
394
402
|
AND e.dedupe_key = ?
|
|
395
403
|
AND e.received_at >= ?
|
|
396
|
-
LIMIT 1`).get(
|
|
404
|
+
LIMIT 1`).get($.specId,$.dedupeKey,$.sinceIso)}hasRecentEventRunForSpec($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
|
|
397
405
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
398
406
|
WHERE r.spec_id = ?
|
|
399
407
|
AND r.trigger_kind = 'event'
|
|
400
408
|
AND e.received_at >= ?
|
|
401
|
-
LIMIT 1`).get(
|
|
409
|
+
LIMIT 1`).get($.specId,$.sinceIso)}findQueuedEventRunForDedupe($){let f=this.db.prepare(`SELECT r.* FROM cron_runs r
|
|
402
410
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
403
411
|
WHERE r.spec_id = ?
|
|
404
412
|
AND r.trigger_kind = 'event'
|
|
405
413
|
AND r.status = 'queued'
|
|
406
414
|
AND e.dedupe_key = ?
|
|
407
415
|
ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
|
|
408
|
-
LIMIT 1`).get(
|
|
416
|
+
LIMIT 1`).get($.specId,$.dedupeKey);return f?B7(f):void 0}updateQueuedEventRunForDebounce($){let f=z0();if((this.db.prepare(`UPDATE cron_runs SET
|
|
409
417
|
trigger_event_id = ?,
|
|
410
418
|
scheduled_for = ?,
|
|
411
419
|
updated_at = ?
|
|
412
420
|
WHERE run_id = ?
|
|
413
421
|
AND trigger_kind = 'event'
|
|
414
|
-
AND status = 'queued'`).run(
|
|
422
|
+
AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,f,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,f){return!!this.db.prepare(`SELECT run_id FROM cron_runs
|
|
415
423
|
WHERE spec_id = ? AND spec_revision = ?
|
|
416
424
|
AND trigger_kind = 'one_off'
|
|
417
|
-
LIMIT 1`).get(f
|
|
425
|
+
LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${r4()}`,J=z0();this.db.prepare(`INSERT INTO cron_runs (
|
|
418
426
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
419
427
|
scheduled_for, trigger_event_id, attempt_count,
|
|
420
428
|
created_at, updated_at
|
|
421
|
-
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(
|
|
422
|
-
WHERE spec_id = ? AND status = 'queued'`).run(
|
|
429
|
+
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId($.specId,f);let Q=this.getRun(f);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
|
|
430
|
+
WHERE spec_id = ? AND status = 'queued'`).run(z0(),$).changes??0}claimDueRuns($){let f=$.nowIso,J=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(f).getTime()+J).toISOString(),Z=Math.max(1,Math.floor($.limit??25)),W=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
|
|
423
431
|
WHERE (
|
|
424
432
|
status = 'queued'
|
|
425
433
|
OR (
|
|
@@ -431,7 +439,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
431
439
|
)
|
|
432
440
|
AND (scheduled_for IS NULL OR scheduled_for <= ?)
|
|
433
441
|
ORDER BY COALESCE(scheduled_for, created_at) ASC
|
|
434
|
-
LIMIT ?`).all(
|
|
442
|
+
LIMIT ?`).all(f,f,Z);for(let X of j){let Y=s(X.run_id);if(!Y)continue;let V=`cclaim_${r4()}`;if((this.db.prepare(`UPDATE cron_runs SET
|
|
435
443
|
status = 'running',
|
|
436
444
|
claim_token = ?,
|
|
437
445
|
claim_started_at = ?,
|
|
@@ -452,8 +460,8 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
452
460
|
AND claim_until_at <= ?
|
|
453
461
|
AND completed_at IS NULL
|
|
454
462
|
)
|
|
455
|
-
)`).run(
|
|
456
|
-
WHERE run_id = ? AND claim_token = ?`).run(J,
|
|
463
|
+
)`).run(V,f,Q,f,f,Y,f).changes??0)!==1)continue;let H=this.getRun(Y);if(!H)continue;W.push({run:H,claimToken:V,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return W}renewClaim($,f,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
|
|
464
|
+
WHERE run_id = ? AND claim_token = ?`).run(J,z0(),$,f).changes??0)===1}completeRun($,f){let J=f.completedAtIso??z0(),Q=f.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
|
|
457
465
|
status = ?,
|
|
458
466
|
session_id = COALESCE(?, session_id),
|
|
459
467
|
report_path = COALESCE(?, report_path),
|
|
@@ -463,7 +471,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
463
471
|
claim_token = NULL,
|
|
464
472
|
claim_until_at = NULL,
|
|
465
473
|
updated_at = ?
|
|
466
|
-
${Q}`).run(
|
|
474
|
+
${Q}`).run(f.status,f.sessionId??null,f.reportPath??null,f.error??null,J,J,$,...f.claimToken?[f.claimToken]:[]).changes??0)>0}requeueRun($){let f=z0();return(this.db.prepare(`UPDATE cron_runs SET
|
|
467
475
|
status = 'queued',
|
|
468
476
|
claim_started_at = NULL,
|
|
469
477
|
claim_token = NULL,
|
|
@@ -475,40 +483,40 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
475
483
|
error = ?,
|
|
476
484
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
477
485
|
updated_at = ?
|
|
478
|
-
WHERE run_id = ? AND claim_token = ?`).run(
|
|
479
|
-
`).trim()}function
|
|
480
|
-
`)[0]??Z);return
|
|
481
|
-
`,{encoding:"utf8",mode:384}),await
|
|
482
|
-
`,"utf8");try{return await $()}finally{await qY(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await nT(J),H=j?Date.now()-Date.parse(j.acquiredAt):NY+1;if(!j||!pT(j.pid)||H>NY){await qY(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await rT(uT)}}async function Bf(f){try{let $=await fetch(oZ(f));if(!$.ok)return;return await $.json()}catch{return}}function Jf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function oZ(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function hY(f){return xT(f)}import{CLINE_HUB_DEV_PORT as aT,CLINE_HUB_PORT as tT,resolveClineBuildEnv as sT}from"@cline/shared";var oT="CLINE_HUB_HOST",eT="CLINE_HUB_PORT",fz="CLINE_HUB_PATHNAME",eZ="127.0.0.1",fW=tT,$W="/hub";function bY(f){return sT(f)==="development"?aT:fW}function JW(f={}){return(f.env??process.env)[oT]?.trim()||eZ}function T2(f={}){let J=(f.env??process.env)[eT]?.trim();if(!J)return bY(f);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return bY(f);return Q}function QW(f={}){return(f.env??process.env)[fz]?.trim()||$W}function r0(f={},$={}){return{host:f.host??JW($),port:f.port??T2($),pathname:f.pathname??QW($)}}var $z="shared:cline";function kY(f){let $=xf(f.trim());return uf(`workspace:${$||f.trim()}`)}function A0(f=$z){return uf(f)}var Bz=8000,Kz=200,Pz=3000,Gz=100,Fz=[100,250,500,1000,2000],Uz="--cline-hub-daemon";function Rz(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function Dz(){try{let f=Xz(uJ(),"logs","hub-daemon.log");return Zz(Hz(f),{recursive:!0}),{fd:Wz(f,"a"),logPath:f}}catch{return}}function dJ(f){let $=f.buildId?.trim();return!!$&&$===z$()}async function R1(f){try{return await Bf(f)}catch{return}}async function Lz(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await R1(f))?.url)return!0;await new Promise((Z)=>setTimeout(Z,Gz))}return!1}async function lJ(f,$){if(dJ(f))return;if(await pJ(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await Lz(f.url,Pz),await p0($).catch(()=>{return})}function _z(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return Az(new URL(`./entry.${f}`,import.meta.url))}function Oz(f,$){let J=_z(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=jz(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=W?[Uz]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...H,"--cwd",f,...Rz($)],cwd:f,env:{...Vz(process.env),CLINE_NO_INTERACTIVE:"1",[Yz]:"1"}}}function Tz(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 ZW(f,$={}){if(IY())return;let J=Oz(f,$),Q=Dz();try{Jz(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)Qz(Q.fd)}}async function z2(f,$={}){for(let J=0;;J++)try{ZW(f,$);return}catch(Q){let Z=Fz[J];if(!Tz(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function S5(f,$={}){if(IY())return;let J=A0(),Q=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=r0($),W=Jf(Z.host,Z.port,Z.pathname);P0(J.discoveryPath).then(async(j)=>{if(j?.url){let Y=await R1(j.url);if(Y?.url&&dJ(Y)&&await Kf(Y.url,{authToken:j.authToken}))return;if(Y?.url)await lJ({...Y,authToken:j.authToken},J.discoveryPath);else await p0(J.discoveryPath).catch(()=>{return})}let H=await R1(W);if(H?.url)await lJ(H,J.discoveryPath);let A=!Q&&Z.port!==0?{...Z,port:0}:Z;await z2(f,A)}).catch(()=>{})}async function xY(f,$={}){let J=A0(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=r0($),j=Jf(W.host,W.port,W.pathname),H=(K)=>{if(!Q)M$(K.url,K.authToken);return K},X=await P0(J.discoveryPath);if(X?.url){let K=await R1(X.url);if(K?.url&&dJ(K)&&await Kf(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await lJ({...K,authToken:X.authToken},J.discoveryPath);else await p0(J.discoveryPath).catch(()=>{return})}let A=await R1(j);if(A?.url)await lJ(A,J.discoveryPath);let V=!Z&&W.port!==0?{...W,port:0}:W;await z2(f,V);let B=Date.now()+Bz;while(Date.now()<B){let K=await P0(J.discoveryPath);if(K?.url){let R=await R1(K.url);if(R?.url&&dJ(R)&&await Kf(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let P=await R1(j);if(P?.url&&!dJ(P))await lJ(P,J.discoveryPath);await new Promise((R)=>setTimeout(R,Kz))}throw Error("Timed out waiting for detached hub startup.")}function Nz(){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 uY(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 uY(f.data);return String(f)}function qz(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 mY(f){let $=f,J=qz($.reason);return new M0("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:WW,{closeCode:$.code,closeReason:J||void 0})}function yz(f,$){if(f instanceof M0)return f;if(f instanceof Error)return new M0("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new M0("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 M0("hub_connect_failed",J);let Q=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new M0("hub_connect_failed",Q?`Failed to connect to hub at ${$.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var wz=8000,Cz=200,gY="*",vY=8000,Sz="cline-hub-auth.",dY=new Map,lY=new Set,Ez=3000,hz=3000,bz=100,WW="Hub connection closed",kz=250,Iz=5000,cY=0.5;class M0 extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function XW(f){return f instanceof M0}class M2 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function E5(f,$){return f instanceof M2&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function pY(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=AW(f.toString());return J?dY.get(J):void 0}function xz(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 AW(f){if(!xz(f))return;let $=new URL(N$(f));return $.search="",$.hash="",$.toString()}function jW(f){let $=AW(f);return!!$&&lY.has($)}function M$(f,$){let J=AW(f);if(J){if(lY.add(J),$?.trim())dY.set(J,$)}return f}class Qf{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new M0("hub_connection_closed",WW);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()||pY(f);f.hash="";let Q=new(Nz())(f.toString(),$?[`${Sz}${$}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new M0("hub_connect_timeout",`Timed out connecting to hub after ${vY}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},vY);Q.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),W()}),Q.addEventListener("error",(A)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=yz(A,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(A)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=mY(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(uY(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=mY(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,Q={listener:f,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,Q){let Z=0,W=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce(f,$,J,Q){await this.connect();let Z=zz("hubreq_"),W=Mz(f,Q?.timeoutMs),j=new Promise((X,A)=>{let Y=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;A(new M2(f,"hub_command_timeout",`Hub command ${f} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(V)=>{if(Y)clearTimeout(Y);X(V)},reject:(V)=>{if(Y)clearTimeout(Y);A(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:$}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===P1){let X=J??(typeof $?.sessionId==="string"?$.sessionId:void 0);throw new vf(X,H.error.message)}throw new M2(f,H.error?.code,H.error?.message??`Hub command ${f} failed`)}return H}async recoverLocalHubTransport(f){if(!jW(this.currentUrl)||!XW(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(kz*2**this.reconnectAttempt,Iz),$=Math.round(f*(1-cY)+Math.random()*f*cY);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(!jW(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 M0("hub_connection_closed",WW),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 M0("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),Q=(this.subscriptionCounts.get(J)??0)+$;if(Q<=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,Q),$>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??gY}subscriptionSessionIdFromKey(f){return f===gY?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 N$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function Kf(f,$){let J=new Qf({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 HW(f,$){let J=N$(f),Q=await Bf(J);if(!Q)return{status:"unreachable",url:J};let Z=z$(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await Kf(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function mz(f){let $=Date.now()+wz;while(Date.now()<$){let J=await P0(f.discoveryPath);if(J?.url){let Q=await HW(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return M$(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,Cz))}return}async function gz(f){let $=Date.now()+hz;while(Date.now()<$){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,bz))}return!1}function vz(f,$){try{return N$(f)===N$($)}catch{return!1}}function cz(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function uz(f,$,J){let Q=new Qf({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:Ez});return!cz(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function rJ(f={}){if(f.endpoint?.trim()){let Z=await HW(f.endpoint);return Z.status==="compatible"?Z.url:void 0}let $=A0(),J=await P0($.discoveryPath);if(!J?.url)return;let Q=await HW(J.url);if(Q.status==="compatible")return M$(Q.url,J.authToken);if(Q.status==="build_mismatch")await p0($.discoveryPath).catch(()=>{return});return}async function D1(f={}){let $=await rJ(f);if($&&await Kf($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=A0();return await z2(f.workspaceRoot??process.cwd()),await mz(J)}async function pJ(f,$){let J=new URL(f),Q=$?.trim()||pY(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function YW(){let f=A0(),$=await P0(f.discoveryPath);if(!$?.url)return!1;try{if(await pJ($.url,$.authToken))return!0}catch{}return!1}async function h5(f){if(!jW(f.url))return;let $=A0(),J=await P0($.discoveryPath);if(!J?.url||!vz(J.url,f.url))return;if(!await uz(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await YW())return;if(!await gz(J.url))return;return await p0($.discoveryPath).catch(()=>{return}),await D1({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}var ZV={};q(ZV,{HubRuntimeHost:()=>df});import{captureSdkError as iY,createSessionId as nY,HUB_CHECKPOINT_CAPABILITY as rz,HUB_COMPACTION_CAPABILITY as iz,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as nz,HUB_HOOK_CAPABILITY_PREFIX as az,HUB_MISTAKE_LIMIT_CAPABILITY as tz,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as sz,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as oz,isHubToolExecutorName as ez}from"@cline/shared";var rY={};q(rY,{createCoreSessionSnapshot:()=>Pf,coreSessionSnapshotToRecord:()=>b5});function dz(f){return f?JSON.parse(JSON.stringify(f)):void 0}function lz(f){return f?JSON.parse(JSON.stringify(f)):void 0}function pz(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,Q=(Array.isArray($?.history)?$.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),A=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:H,createdAt:X,runCount:A,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=f?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function Pf(f){let{session:$}=f,J=dz($.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:lz(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let Q=pz(J);return Q?{checkpoint:Q}:{}})()}}function b5(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 N2(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var fM=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function aY(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function tY(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function sY(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 L1(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function oY(f,$){let J={manifest:[],handlers:new Map};for(let Z of Object.keys($.toolExecutors??{}).filter(ez)){let W=$.toolExecutors?.[Z];if(typeof W!=="function")continue;L1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${sz}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],A={...sY(j.context),signal:H};return{result:await W(...X,A)}})}for(let Z of f?.extraTools??[])L1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:N2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:N2(Z.lifecycle)}:{},capabilityName:`${nz}${Z.name}`},async({payload:W,abortSignal:j,progress:H})=>{let X={...sY(W.context),signal:j};return{result:await Z.execute(W.input,{...X,emitUpdate:(Y)=>{H({update:Y})}})}});let Q=f?.hooks;if(Q)for(let Z of fM){let W=Q[Z];if(typeof W!=="function")continue;L1(J,{kind:"hook",name:Z,capabilityName:`${az}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if(f?.compaction?.compact){let Z=f.compaction.compact;L1(J,{kind:"compaction",capabilityName:iz,config:aY(f.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.checkpoint?.createCheckpoint){let Z=f.checkpoint.createCheckpoint;L1(J,{kind:"checkpoint",capabilityName:rz,config:aY(f.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if(f?.onConsecutiveMistakeLimitReached){let Z=f.onConsecutiveMistakeLimitReached;L1(J,{kind:"mistakeLimit",capabilityName:tz},async({payload:W})=>({result:await Z(W.context)}))}if(f?.userInstructionService){let Z=f.userInstructionService;L1(J,{kind:"userInstructionService",capabilityName:oz},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function JV(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message.trim()||void 0;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return}function $M(f){return JV(f)??"Capability request was cancelled."}function JM(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function QM(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function ZM(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,Q=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function eY(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 VW(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function q$(f,$){return VW(f?.[$])??0}function WM(f){let $=f?.delta&&typeof f.delta==="object"?f.delta:void 0,J=f?.totals&&typeof f.totals==="object"?f.totals:void 0,Q=f?.agent&&typeof f.agent==="object"?f.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:q$($,"inputTokens"),outputTokens:q$($,"outputTokens"),cacheReadTokens:q$($,"cacheReadTokens"),cacheWriteTokens:q$($,"cacheWriteTokens"),cost:VW($?.totalCost),totalInputTokens:q$(J,"inputTokens"),totalOutputTokens:q$(J,"outputTokens"),totalCacheReadTokens:q$(J,"cacheReadTokens"),totalCacheWriteTokens:q$(J,"cacheWriteTokens"),totalCost:VW(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function jM(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,Q=QM(J)?J:J==="failed"?"error":"completed",Z=ZM(f?.usage??$?.usage);return{type:"done",reason:Q,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:Z}}function k5(f,$){return f.error?.message??`hub command failed: ${$}`}function iJ(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function QV(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:F0.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:iJ(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:iJ(f.status)==="completed"?0:iJ(f.status)==="failed"?1:void 0,status:iJ(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 y$(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 HM(f){let $=y$(f?.snapshot);if($)return b5($);let J=f?.session;return J?QV(J):void 0}function fV(f,$,J){let Q=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return C0.parse({version:1,session_id:f,source:$.source??F0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:iJ(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:Q,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 $V(f,$){return C0.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 df{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new gJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;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=D0(f.capabilities)??{},this.telemetry=f.telemetry,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 Qf({...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(!E5(f,"session.create"))return!1;let $=await h5({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=oY(f.localRuntime,$),Q=f.config.sessionId?.trim()||nY(),Z=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:N2({...f.config,sessionId:Q}),metadata:{...f.sessionMetadata??{},source:f.source??F0.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:N2(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(Q,$,J.handlers);let W;try{W=await Z()}catch(A){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(Q,$,J.handlers);try{W=await Z()}catch(Y){throw this.cleanupPlannedSession(Q),Y}}else throw A}let j=y$(W.payload?.snapshot),H=W.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(X!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(X,$,J.handlers);return{sessionId:X,manifest:j?$V(j,f):fV(X,f,H),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 Q=f.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?oY(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||nY():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let H;try{H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??f.cwd,sessionConfig:N2({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:N2(Q.toolPolicies)}:{}},$)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=y$(H.payload?.snapshot),A=H.payload?.session,Y=(X?.sessionId??A?.sessionId)?.trim();if(J&&!Y){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(Y&&j&&Y!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(Y&&Z)this.sessionCapabilities.set(Y,Z);if(Y&&W.handlers.size>0)this.sessionClientContributionHandlers.set(Y,W.handlers);if(Y)this.ensureSessionSubscription(Y);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:Y,startResult:Y?{sessionId:Y,manifest:X?$V(X,Q??{}):fV(Y,Q??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,mode:f.mode,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=y$($.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let Q=$.payload?.session,Z=eY(Q?.usage),W=eY(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:JV($)},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 $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(cf(J))return;throw J}return HM($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((Z)=>{let W=y$(Z);return W?[b5(W)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(QV)}async listSettings(f){let $=await this.client.command("settings.list",tY(f));if(!$.ok)throw Error(k5($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",tY(f));if(!$.ok)throw Error(k5($,"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 iY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(k5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:$,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(k5(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}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((Q)=>{this.handleHubEvent(Q)},{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 D0(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:jM(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,f)});return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,f)});return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=y$(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.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:"",Q=f.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});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=WM(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=y$(f.payload?.snapshot),Q=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:Q?.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=y$(f.payload?.snapshot),Q=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:Q}}),J?.interactive===!0&&J0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:$,reason:Q,ts:f.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError(f,$,J){try{iY(this.telemetry,{component:"core",operation:f,error:$,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}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 Q=typeof f.payload?.requestId==="string"?f.payload.requestId:"",Z=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get($)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${$}.`},$).catch(()=>{});return}let j=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(Q,H);let X=(A)=>{this.client.command("capability.progress",{requestId:Q,payload:A},$).catch((Y)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",Y,f)})};try{let A=await W({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:A},$)}catch(A){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:A instanceof Error?A.message:String(A)},$)}finally{this.activeCapabilityAbortControllers.delete(Q)}}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($M(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 Q=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",Z=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",W=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!Q||!Z||!W)return;let j=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},H=JM(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:$,toolCallId:Z,toolName:W,toolInput:H});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:Z,toolName:W,input:H,policy:j})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:X.approved,reason:X.reason},$).catch(()=>{})}}var WV={};q(WV,{RemoteRuntimeHost:()=>q2});class q2 extends df{constructor(f){super({url:N$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var jV={};q(jV,{SqliteSessionStore:()=>Ff});import{existsSync as XM,mkdirSync as AM}from"node:fs";import{join as YM}from"node:path";import{asBool as nJ,asOptionalString as Gf,asString as lf,ensureSessionSchema as VM,loadSqliteDb as BM,nowIso as I5,toBoolInt as aJ}from"@cline/shared/db";import{resolveDbDataDir as KM}from"@cline/shared/storage";class Ff{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??KM()}init(){this.getRawDb()}ensureSessionsDir(){if(!XM(this.sessionsDirPath))AM(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return YM(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=BM(this.sessionDbPath());return VM(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 $=I5();this.run(`INSERT OR REPLACE INTO sessions (
|
|
486
|
+
WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,z0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,z0(),$)}}class n4{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new i4({dbPath:$.dbPath});let f=$.specs;this.reconciler=new X7({store:this.store,specs:f}),this.materializer=new u4({store:this.store}),this.eventIngress=new sZ({store:this.store,logger:$.logger}),this.runner=new d4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Y7({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var oB={};w(oB,{manifestToSessionRecord:()=>I5,listSessionHistoryFromBackend:()=>F7,listSessionHistory:()=>x5,hydrateSessionHistory:()=>tB});import{readdir as FM,readFile as nB}from"node:fs/promises";import{join as aB}from"node:path";import{formatDisplayUserInput as PM,normalizeUserInput as DM}from"@cline/shared";import{resolveSessionDataDir as sB}from"@cline/shared/storage";import{existsSync as AM}from"node:fs";import{readFile as KM}from"node:fs/promises";import{formatDisplayUserInput as lB}from"@cline/shared";class a4{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function M$($){let f=$?.trim();if(!f||!AM(f))return[];try{let J=(await KM(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return pB(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return pB(Z)}return[]}catch{return[]}}function GM($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:lB($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:lB(f.text)}})}}function pB($){return $.map(GM)}function A7($){return $?{...$}:void 0}async function rB($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function s4($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function r0($){let f=s4($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function k5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function RM($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function G7($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function UM($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function zM($){return $.isSubagent!==!0&&!s4($.parentSessionId)}function LM($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function I5($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function _M($){let f=G7($);if(f===0)return[];let J=sB(),Z=(await FM(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:LM(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let Y=aB(J,X,`${X}.json`),V=await nB(Y,"utf8").catch(()=>{return});if(!V)return;let B;try{B=JSON.parse(V)}catch{return}let H=y0.safeParse(B);if(!H.success)return;return I5(H.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function OM($,f,J){let Q=G7(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:UM(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter(zM)).slice(0,Q)}function MM($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
|
|
487
|
+
`).trim()}function iB($){return $.replace(/\s+/g," ").trim()}function TM($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function NM($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let Q=iB(MM(J.content));if(!Q)continue;let Z=f==="user"?iB(PM(Q)):Q,W=DM(Z.split(`
|
|
488
|
+
`)[0]??Z);return TM(W,50)}return}function qM($){let f=0;for(let J of $)f+=k5(J.metrics?.cost)??0;return f}function wM($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=r0(Z.modelInfo?.provider);if(!J)J=r0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function yM($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function SM($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function K7($,f){let J=RM($.metadata),Q=s4(f?.title)??s4(J?.title),Z=k5(f?.totalCost)??k5(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:r0(f?.provider)??r0($.provider)??yM(J)??"",model:r0(f?.model)??r0($.model)??SM(J)??"",metadata:W}}function CM($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function EM($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!CM(J)}async function hM($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await $.readSessionMessages(J.sessionId);return EM(J,Q)?{...J,status:"idle"}:J}))}async function tB($,f){return await Promise.all(f.map(async(J)=>{let Q=K7(J),Z=Boolean(s4(Q.metadata?.title)),W=Boolean(r0(Q.provider)),j=Boolean(r0(Q.model)),X=k5(Q.metadata?.totalCost),Y=X!==void 0&&X>0;if(Z&&W&&j&&Y)return Q;let V=await $.readSessionMessages(J.sessionId);if(V.length===0)return Q;let B=wM(V),H=qM(V);return K7(J,{title:Z?void 0:NM(V),provider:W?void 0:B.provider,model:j?void 0:B.model,totalCost:Y||H<=0?void 0:H})}))}async function x5($,f={}){let J=G7(f.limit),Q=f.includeSubagents===!0,Z=await OM($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await _M(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let V of[...Z,...W]){if(j.has(V.sessionId))continue;j.set(V.sessionId,V)}let X=W.length===0?Z:Array.from(j.values()).sort((V,B)=>B.startedAt.localeCompare(V.startedAt)).slice(0,J),Y=await hM($,X);if(f.hydrate===!1)return Y.map((V)=>K7(V));return await tB($,Y)}async function bM($){let f=$.trim();if(!f)return;let J=aB(sB(),f,`${f}.json`),Q=await nB(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=y0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function F7($,f={}){let J=new Map;return await x5({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(s8)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await bM(Z);return await M$(W)}},f)}var HA={};w(HA,{resolveSessionBackend:()=>t7,createRuntimeHost:()=>d2});import{captureSdkError as VA}from"@cline/shared";import{createSessionId as wT,isHubProtocolCompatible as yT,resolveClineBuildEnv as ST,resolveHubCommandTimeoutMs as CT}from"@cline/shared";import{spawn as WT}from"node:child_process";import{closeSync as jT,mkdirSync as XT,openSync as YT}from"node:fs";import{basename as VT,dirname as BT,join as HT}from"node:path";import{fileURLToPath as AT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as KT,isHubDaemonProcess as AH,isHubProtocolCompatible as GT,resolveClineBuildEnv as KH,withResolvedClineBuildEnv as FT}from"@cline/shared";import{createHash as kM,randomBytes as IM}from"node:crypto";import{existsSync as xM}from"node:fs";import{chmod as gM,mkdir as P7,readFile as QH,rm as D7,writeFile as ZH}from"node:fs/promises";import{dirname as WH,join as R7}from"node:path";import{resolveClineDataDir as Rf,resolveClineDir as jH}from"@cline/shared/storage";var $H="0.0.47-nightly.1781493618";var t4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:$H,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var mM="CLINE_HUB_DISCOVERY_PATH",vM="CLINE_HUB_BUILD_ID",fH=30000,cM=15000,uM=100;function dM($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function lM($){return kM("sha256").update($).digest("hex").slice(0,12)}function pM($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function g5(){return IM(32).toString("hex")}function rM($){return new Promise((f)=>setTimeout(f,$))}function iM($){return`${$}.lock`}async function nM($){try{let f=JSON.parse(await QH(R7($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function JH($){await D7($,{recursive:!0,force:!0}).catch(()=>{return})}function m5(){return process.env[vM]?.trim()||String(t4.version)}function d1($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${lM($)}`,J=process.env[mM]?.trim()||R7(Rf(),"locks","hub","owners",`${dM(f)}.json`);return{ownerId:f,discoveryPath:J}}function XH($=`hub-${Date.now().toString(36)}`){return d1($)}async function H0($){try{let f=JSON.parse(await QH($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,minClientProtocolVersion:typeof f.minClientProtocolVersion==="string"?f.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof f.maxClientProtocolVersion==="string"?f.maxClientProtocolVersion:void 0,capabilities:Array.isArray(f.capabilities)?f.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function v5($,f){await P7(WH($),{recursive:!0}),await D7($,{force:!0}).catch(()=>{return}),await ZH($,`${JSON.stringify(f,null,2)}
|
|
489
|
+
`,{encoding:"utf8",mode:384}),await gM($,384)}async function C0($){await D7($,{force:!0}).catch(()=>{return})}async function c5($,f){let J=iM($);await P7(WH(J),{recursive:!0});let Q=Date.now()+cM;while(!0)try{await P7(J,{recursive:!1}),await ZH(R7(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
490
|
+
`,"utf8");try{return await f()}finally{await JH(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await nM(J),X=j?Date.now()-Date.parse(j.acquiredAt):fH+1;if(!j||!pM(j.pid)||X>fH){await JH(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await rM(uM)}}async function l1($,f){try{let J=await fetch(f?.authToken?U7($):u5($),{headers:f?.authToken?{authorization:`Bearer ${f.authToken}`}:void 0});if(!J.ok)return;let Q=await J.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function Z1($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function u5($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function U7($){let f=new URL(u5($));return f.pathname="/status",f.toString()}function YH($){return xM($)}import{CLINE_HUB_DEV_PORT as aM,CLINE_HUB_PORT as sM,resolveClineBuildEnv as tM}from"@cline/shared";var oM="CLINE_HUB_HOST",eM="CLINE_HUB_PORT",$T="CLINE_HUB_PATHNAME",z7="127.0.0.1",L7=sM,_7="/hub";function VH($){return tM($)==="development"?aM:L7}function O7($={}){return($.env??process.env)[oM]?.trim()||z7}function C2($={}){let J=($.env??process.env)[eM]?.trim();if(!J)return VH($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return VH($);return Q}function M7($={}){return($.env??process.env)[$T]?.trim()||_7}function i0($={},f={}){return{host:$.host??O7(f),port:$.port??C2(f),pathname:$.pathname??M7(f)}}import{join as fT}from"node:path";var JT="shared:cline",QT="CLINE_HUB_DISCOVERY_PATH",ZT="hub-production";function BH($){let f=g1($.trim());return d1(`workspace:${f||$.trim()}`)}function E0($=JT){return d1($)}function n0(){return{ownerId:ZT,discoveryPath:process.env[QT]?.trim()||fT(Rf(),"locks","hub","production.json")}}var PT=8000,DT=200,RT=3000,UT=100,zT=[100,250,500,1000,2000],LT="--cline-hub-daemon";function _T($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function OT(){try{let $=HT(Rf(),"logs","hub-daemon.log");return XT(BT($),{recursive:!0}),{fd:YT($,"a"),logPath:$}}catch{return}}function GH(){return KH()==="production"?n0():E0()}function Uf($){return GT($).compatible}function HH($,f,J){if(!f||f.url!==J)return $;return{...$,authToken:$.authToken??f.authToken,pid:$.pid??f.pid}}async function zf($,f){try{return await l1($,{authToken:f})}catch{return}}async function MT($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await zf($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,UT))}return!1}async function d5($,f){if(await e4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let J=await MT($.url,RT);return await C0(f).catch(()=>{return}),J}async function o4($,f){if(Uf($))return!0;return d5($,f)}async function FH($){if(KH()!=="production")return;let f=E0();if(f.discoveryPath===$.discoveryPath)return;let J=await H0(f.discoveryPath);if(J?.url)await d5(J,f.discoveryPath);else await C0(f.discoveryPath).catch(()=>{return})}function TT(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return AT(new URL(`./entry.${$}`,import.meta.url))}function NT($,f){let J=TT(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=VT(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[LT]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,..._T(f)],cwd:$,env:{...FT(process.env),CLINE_NO_INTERACTIVE:"1",[KT]:"1"}}}function qT($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function T7($,f={}){if(AH())return;let J=NT($,f),Q=OT();try{WT(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd,windowsHide:!0}).unref()}finally{if(Q)jT(Q.fd)}}async function E2($,f={}){for(let J=0;;J++)try{T7($,f);return}catch(Q){let Z=zT[J];if(!qT(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function l5($,f={}){if(AH())return;let J=GH(),Q=i0(f),Z=Z1(Q.host,Q.port,Q.pathname),W=f.allowPortFallback===!0&&Q.port!==0;FH(J).catch(()=>{return}).then(()=>H0(J.discoveryPath)).then(async(j)=>{let X=!1;if(j?.url)if(!j.authToken){if(X=!0,!await d5(j,J.discoveryPath)&&!W)return}else{let B=await zf(j.url,j.authToken);if(B?.url&&Uf(B)&&await G1(B.url,{authToken:j.authToken}))return;if(B?.url)await o4({...B,authToken:j.authToken},J.discoveryPath);else await C0(J.discoveryPath).catch(()=>{return})}let Y=await zf(Z);if(Y?.url){if(Uf(Y)){if(!W||!X)return}else if(!await o4({...Y,authToken:void 0},J.discoveryPath)&&!W)return}let V=W?{...Q,port:0}:Q;await E2($,V)}).catch(()=>{})}async function PH($,f={}){let J=GH(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=i0(f),W=Z1(Z.host,Z.port,Z.pathname),j=(K)=>{if(!Q)T$(K.url,K.authToken);return K};await FH(J).catch(()=>{return});let X=await H0(J.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await d5(X,J.discoveryPath);else{let G=await zf(X.url,K);if(G?.url&&Uf(G)&&await G1(G.url,{authToken:K}))return j({url:G.url,authToken:K});if(G?.url)await o4({...G,authToken:K},J.discoveryPath);else await C0(J.discoveryPath).catch(()=>{return})}}let V=await zf(W);if(V?.url){let K=HH(V,X,W);if(Uf(V))throw Error(`A compatible Cline Hub is already running at ${W}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await o4(K,J.discoveryPath)&&f.allowPortFallback!==!0&&Z.port!==0)throw Error(`An incompatible Cline Hub is already running at ${W} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let H=f.allowPortFallback===!0&&Z.port!==0?{...Z,port:0}:Z;await E2($,H);let A=Date.now()+PT;while(Date.now()<A){let K=await H0(J.discoveryPath);if(K?.url&&K.authToken){let R=await zf(K.url,K.authToken);if(R?.url&&Uf(R)&&await G1(R.url,{authToken:K.authToken}))return j({url:R.url,authToken:K.authToken})}let G=await zf(W);if(G?.url&&!Uf(G)){let R=HH(G,K,W);if(!await o4(R,J.discoveryPath)&&f.allowPortFallback!==!0&&Z.port!==0)throw Error(`An incompatible Cline Hub is still running at ${W} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,DT))}throw Error("Timed out waiting for detached hub startup.")}function p5(){return ST()==="production"?n0():E0()}function ET(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function LH($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return LH($.data);return String($)}function hT($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function DH($){let f=$,J=hT(f.reason);return new T0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:N7,{closeCode:f.code,closeReason:J||void 0})}function bT($,f){if($ instanceof T0)return $;if($ instanceof Error)return new T0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new T0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new T0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new T0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var kT=8000,IT=200,RH="*",UH=8000,xT="cline-hub-auth.",_H=new Map,OH=new Set,gT=3000,mT=3000,vT=100,N7="Hub connection closed",cT=250,uT=5000,zH=0.5;class T0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function y7($){return $ instanceof T0}class h2 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function r5($,f){return $ instanceof h2&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function MH($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=S7($.toString());return J?_H.get(J):void 0}function dT($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function S7($){if(!dT($))return;let f=new URL(N$($));return f.search="",f.hash="",f.toString()}function q7($){let f=S7($);return!!f&&OH.has(f)}function T$($,f){let J=S7($);if(J){if(OH.add(J),f?.trim())_H.set(J,f)}return $}class W1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new T0("hub_connection_closed",N7);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||MH($);$.hash="";let Q=new(ET())($.toString(),f?[`${xT}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new T0("hub_connect_timeout",`Timed out connecting to hub after ${UH}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},UH);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),W()}),Q.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=bT(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!Z)this.lastCloseError=DH(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(LH(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=DH(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=wT("hubreq_"),W=CT($,Q?.timeoutMs),j=new Promise((Y,V)=>{let B=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;V(new h2($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(H)=>{if(B)clearTimeout(B);Y(H)},reject:(H)=>{if(B)clearTimeout(B);V(H)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(Y){throw this.pendingReplies.delete(Z),Y}let X=await j;if(!X.ok){if(X.error?.code===Gf){let Y=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new c1(Y,X.error.message)}throw new h2($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!q7(this.currentUrl)||!y7($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await Lf({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(cT*2**this.reconnectAttempt,uT),f=Math.round($*(1-zH)+Math.random()*$*zH);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!q7(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await Lf({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new T0("hub_connection_closed",N7),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new T0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??RH}subscriptionSessionIdFromKey($){return $===RH?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function N$($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function G1($,f){let J=new W1({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function w7($,f){let J=N$($),Q=await l1(J,{authToken:f?.authToken});if(!Q)return{status:"unreachable",url:J};if(!yT(Q).compatible)return{status:"protocol_mismatch",url:J};if(f?.verifyConnection===!0&&!await G1(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function lT($){let f=Date.now()+kT;while(Date.now()<f){let J=await H0($.discoveryPath);if(J?.url){let Q=await w7(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return T$(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,IT))}return}async function pT($){let f=Date.now()+mT;while(Date.now()<f){if(!(await l1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,vT))}return!1}function rT($,f){try{return N$($)===N$(f)}catch{return!1}}function iT($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function nT($,f,J){let Q=new W1({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:gT});return!iT(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function $6($={}){if($.endpoint?.trim()){let Z=await w7($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=p5(),J=await H0(f.discoveryPath);if(!J?.url)return;let Q=await w7(J.url,{authToken:J.authToken});if(Q.status==="compatible")return T$(Q.url,J.authToken);if(Q.status==="protocol_mismatch")await C0(f.discoveryPath).catch(()=>{return});return}async function Lf($={}){let f=await $6($);if(f&&await G1(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=p5();return await E2($.workspaceRoot??process.cwd()),await lT(J)}async function e4($,f){let J=new URL($),Q=f?.trim()||MH(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function C7($=p5()){let f=await H0($.discoveryPath);if(!f?.url)return!1;try{if(await e4(f.url,f.authToken))return!0}catch{}return!1}async function i5($){if(!q7($.url))return;let f=p5(),J=await H0(f.discoveryPath);if(!J?.url||!rT(J.url,$.url))return;if(!await nT(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await C7())return;if(!await pT(J.url))return;return await C0(f.discoveryPath).catch(()=>{return}),await Lf({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var xH={};w(xH,{HubRuntimeHost:()=>p1});import{captureSdkError as NH,createSessionId as qH,HUB_CHECKPOINT_CAPABILITY as oT,HUB_COMPACTION_CAPABILITY as eT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as $N,HUB_HOOK_CAPABILITY_PREFIX as fN,HUB_MISTAKE_LIMIT_CAPABILITY as JN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as QN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ZN,isHubToolExecutorName as WN}from"@cline/shared";var TH={};w(TH,{createCoreSessionSnapshot:()=>F1,coreSessionSnapshotToRecord:()=>n5});function aT($){return $?JSON.parse(JSON.stringify($)):void 0}function sT($){return $?JSON.parse(JSON.stringify($)):void 0}function tT($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",Y=Number(j.createdAt),V=Number(j.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function F1($){let{session:f}=$,J=aT(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:sT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=tT(J);return Q?{checkpoint:Q}:{}})()}}function n5($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function b2($){if(!$)return;return JSON.parse(JSON.stringify($))}var jN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function wH($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function yH($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function SH($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function _f($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function CH($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(WN)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;_f(J,{kind:"toolExecutor",executor:Z,capabilityName:`${QN}${Z}`},async({payload:j,abortSignal:X})=>{let Y=Array.isArray(j.args)?[...j.args]:[],V={...SH(j.context),signal:X};return{result:await W(...Y,V)}})}for(let Z of $?.extraTools??[])_f(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:b2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:b2(Z.lifecycle)}:{},capabilityName:`${$N}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let Y={...SH(W.context),signal:j};return{result:await Z.execute(W.input,{...Y,emitUpdate:(B)=>{X({update:B})}})}});let Q=$?.hooks;if(Q)for(let Z of jN){let W=Q[Z];if(typeof W!=="function")continue;_f(J,{kind:"hook",name:Z,capabilityName:`${fN}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;_f(J,{kind:"compaction",capabilityName:eT,config:wH($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;_f(J,{kind:"checkpoint",capabilityName:oT,config:wH($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;_f(J,{kind:"mistakeLimit",capabilityName:JN},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;_f(J,{kind:"userInstructionService",capabilityName:ZN},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function kH($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function XN($){return kH($)??"Capability request was cancelled."}function YN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function VN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function BN($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function EH($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function E7($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function q$($,f){return E7($?.[f])??0}function HN($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:q$(f,"inputTokens"),outputTokens:q$(f,"outputTokens"),cacheReadTokens:q$(f,"cacheReadTokens"),cacheWriteTokens:q$(f,"cacheWriteTokens"),cost:E7(f?.totalCost),totalInputTokens:q$(J,"inputTokens"),totalOutputTokens:q$(J,"outputTokens"),totalCacheReadTokens:q$(J,"cacheReadTokens"),totalCacheWriteTokens:q$(J,"cacheWriteTokens"),totalCost:E7(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function AN($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=VN(J)?J:J==="failed"?"error":"completed",Z=BN($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function a5($,f){return $.error?.message??`hub command failed: ${f}`}function f6($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function IH($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:P0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:f6($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:f6($.status)==="completed"?0:f6($.status)==="failed"?1:void 0,status:f6($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function w$($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function KN($){let f=w$($?.snapshot);if(f)return n5(f);let J=$?.session;return J?IH(J):void 0}function hH($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??P0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:f6(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function bH($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class p1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new a4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=U0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new W1({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!r5($,"session.create"))return!1;let f=await i5({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=CH($.localRuntime,f),Q=$.config.sessionId?.trim()||qH(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:b2({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??P0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:b2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(V){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(B){throw this.cleanupPlannedSession(Q),B}}else throw V}let j=w$(W.payload?.snapshot),X=W.payload?.session,Y=(j?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(Y!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(Y,f,J.handlers);return{sessionId:Y,manifest:j?bH(j,$):hH(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?CH(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||qH():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:b2({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??P0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:b2(Q.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let Y=w$(X.payload?.snapshot),V=X.payload?.session,B=(Y?.sessionId??V?.sessionId)?.trim();if(J&&!B){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(B&&j&&B!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(B&&Z)this.sessionCapabilities.set(B,Z);if(B&&W.handlers.size>0)this.sessionClientContributionHandlers.set(B,W.handlers);if(B)this.ensureSessionSubscription(B);let H=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:B,startResult:B?{sessionId:B,manifest:Y?bH(Y,Q??{}):hH(B,Q??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:H,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=w$(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=EH(Q?.usage),W=EH(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:kH(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(u1(J))return;throw J}return KN(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=w$(Z);return W?[n5(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(IH)}async listSettings($){let f=await this.client.command("settings.list",yH($));if(!f.ok)throw Error(a5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",yH($));if(!f.ok)throw Error(a5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw NH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(a5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(a5(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return U0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:AN($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=w$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=HN($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=w$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=w$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:Q}}),J?.interactive===!0&&W0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{NH(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Q,payload:V},f).catch((B)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",B,$)})};try{let V=await W({payload:j,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:V},f)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:V instanceof Error?V.message:String(V)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(XN($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=YN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let Y=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:Y.approved,reason:Y.reason},f).catch(()=>{})}}var gH={};w(gH,{RemoteRuntimeHost:()=>k2});class k2 extends p1{constructor($){super({url:N$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var mH={};w(mH,{SqliteSessionStore:()=>D1});import{existsSync as GN,mkdirSync as FN}from"node:fs";import{join as PN}from"node:path";import{asBool as J6,asOptionalString as P1,asString as r1,ensureSessionSchema as DN,loadSqliteDb as RN,nowIso as s5,toBoolInt as Q6}from"@cline/shared/db";import{resolveDbDataDir as UN}from"@cline/shared/storage";class D1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??UN()}init(){this.getRawDb()}ensureSessionsDir(){if(!GN(this.sessionsDirPath))FN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return PN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=RN(this.sessionDbPath());return DN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=s5();this.run(`INSERT OR REPLACE INTO sessions (
|
|
483
491
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
484
492
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
485
493
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
486
494
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
487
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
495
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,Q6($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,Q6($.enableTools),Q6($.enableSpawn),Q6($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,Q6($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,f])}update($){let f=[],J=[];if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId);if(f.length===0)return;f.push("updated_at = ?"),J.push(s5()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:W0(f)?null:s5(),exitCode:W0(f)?null:J??(f==="failed"?1:0)})}get($){let f=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
|
|
488
496
|
provider, model, cwd, workspace_root, team_name,
|
|
489
497
|
enable_tools, enable_spawn, enable_teams,
|
|
490
498
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
|
|
491
499
|
prompt, metadata_json, hook_path, messages_path, updated_at
|
|
492
|
-
FROM sessions WHERE session_id = ?`,[
|
|
493
|
-
`,"utf8")}readSessionManifest(
|
|
494
|
-
`;if(
|
|
495
|
-
`,"utf8")}}import{appendFileSync as
|
|
496
|
-
`,"utf8")}}import{formatUserInputBlock as
|
|
500
|
+
FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:r1(f.session_id),source:r1(f.source),pid:Number(f.pid??0),startedAt:r1(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:r1(f.status),interactive:J6(f.interactive),provider:r1(f.provider),model:r1(f.model),cwd:r1(f.cwd),workspaceRoot:r1(f.workspace_root),teamName:P1(f.team_name),enableTools:J6(f.enable_tools),enableSpawn:J6(f.enable_spawn),enableTeams:J6(f.enable_teams),parentSessionId:P1(f.parent_session_id),parentAgentId:P1(f.parent_agent_id),agentId:P1(f.agent_id),conversationId:P1(f.conversation_id),isSubagent:J6(f.is_subagent),prompt:P1(f.prompt),metadata:(()=>{let J=P1(f.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:P1(f.hook_path),messagesPath:P1(f.messages_path),updatedAt:P1(f.updated_at)??s5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let Q of f){let Z=this.get(r1(Q.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}I2();import{existsSync as p7,mkdirSync as Hq,readFileSync as fA,renameSync as Aq,writeFileSync as Kq}from"node:fs";import{join as JA}from"node:path";import{resolveSessionDataDir as Gq}from"@cline/shared/storage";import{dirname as Vq}from"node:path";import{nanoid as Bq}from"nanoid";import{appendFileSync as EN,existsSync as hN,mkdirSync as vH,readFileSync as bN,writeFileSync as cH}from"node:fs";import{dirname as uH,join as kN}from"node:path";import{ensureHookLogDir as IN}from"@cline/shared/storage";class h7{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new hZ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){HY(f,J,sQ($))}writeSessionManifest($,f){vH(uH($),{recursive:!0}),cH($,`${JSON.stringify(y0.parse(f),null,2)}
|
|
501
|
+
`,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!hN(f))return{path:f};try{return{path:f,manifest:y0.parse(JSON.parse(bN(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let Q=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=tQ({updatedAt:e(),context:sQ($),messages:f,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
|
|
502
|
+
`;if(vH(uH(Q),{recursive:!0}),cH(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??kN(IN(),"hooks.jsonl");EN(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:f,pid:J,source:Z})}
|
|
503
|
+
`,"utf8")}}import{appendFileSync as xN}from"node:fs";import{join as gN}from"node:path";import{resolveRootSessionId as dH}from"@cline/shared";import{ensureHookLogDir as mN}from"@cline/shared/storage";import{z as b7}from"zod";var vN="subagent",cN=b7.looseObject({task:b7.string().optional(),systemPrompt:b7.string().optional()});class t5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,Q){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:vN,pid:process.ppid,startedAt:f.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:t8({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=dH($.sessionContext);if(!f)return;let J=cN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let Q=J2(f,$.agentId),Z=await this.adapter.getSession(Q),W=e(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:t8({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=dH($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=J2(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,n8(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let Q=W0(f)?null:e(),Z=W0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,f)}async onTeamTaskStart($,f,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=r8($,f),W=e(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let X=this.teamTaskQueueKey($,f),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(Z),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,f,J,Q,Z,W){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!Y)return;let V=Z?.messages??W,B=this.toPersistedMessages(V,Z,W);if(B)await this.manifestStore.persistSessionMessages(Y,B);await this.applySubagentStatusBySessionId(Y,J),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,f,J,Q){let Z=this.teamTaskQueueKey($,f),W=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!W)return;let j=J.trim();if(!j)return;let X=Q?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),B=this.teamTaskLastHeartbeatBySession.get(W)??0;if(V-B<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===Y)return;this.teamTaskLastProgressLineBySession.set(W,Y)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??gN(mN(),"hooks.jsonl");xN(J,`${JSON.stringify({ts:e(),...$})}
|
|
504
|
+
`,"utf8")}}import{formatUserInputBlock as Yq}from"@cline/shared";var $A={};w($A,{toTeamProgressLifecycleEvent:()=>v2,sanitizeTeamName:()=>fY,reviveTeamStateDates:()=>DJ,parseConfiguredAgentConfig:()=>Z6,loadConfiguredAgentConfigs:()=>x2,createWorkerReviewerTeam:()=>eH,createSpawnAgentTool:()=>H$,createDelegatedAgentConfigProvider:()=>V$,createDelegatedAgent:()=>B$,createConfiguredAgentTools:()=>g2,createAgentTeamsTools:()=>p$,createAgentTeam:()=>x7,buildTeamProgressSummary:()=>m2,buildDelegatedAgentConfig:()=>d$,buildConfiguredAgentToolName:()=>W6,buildConfiguredAgentToolDescriptors:()=>j6,bootstrapAgentTeams:()=>f2,AgentTeamsRuntime:()=>Of,AgentTeam:()=>u2});import{existsSync as uN,readdirSync as dN,readFileSync as lN}from"node:fs";import{basename as lH,extname as pN,join as rN}from"node:path";import{resolveAgentConfigSearchPaths as iN}from"@cline/shared/storage";import rH from"yaml";import{z as N0}from"zod";var iH=N0.object({name:N0.string().trim().min(1),description:N0.string().trim().min(1),tools:N0.union([N0.string(),N0.array(N0.string())]).optional(),skills:N0.union([N0.string(),N0.array(N0.string())]).optional(),providerId:N0.string().trim().min(1).optional(),modelId:N0.string().trim().min(1).optional(),maxIterations:N0.number().int().positive().optional()});function nN($){let f=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!f)throw Error("Missing YAML frontmatter block in agent config file.");let J=f[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=J;let Z,W=Array.from($.matchAll(Q)).filter((j)=>j.index>=J);for(let j of W){let X=j.index,Y=$.slice(J,X);try{let V=rH.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;iH.parse(V);let B=$.slice(X+j[0].length);Z={frontmatter:Y,body:B}}catch{}}if(Z)return Z;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function pH($){if($===void 0)return;let f=Array.isArray($)?$:$.split(",");return Array.from(new Set(f.map((J)=>J.trim()).filter((J)=>J.length>0)))}function aN($){return $.trim().toLowerCase()}function sN($){let f=pN($).toLowerCase();return f===".yml"||f===".yaml"}function Z6($,f={}){let{frontmatter:J,body:Q}=nN($),Z=rH.parse(J);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Agent config frontmatter must be a YAML mapping.");let W=iH.parse(Z),j=Q.trim();if(!j)throw Error("Missing system prompt body in agent config file.");return{name:W.name,description:W.description,tools:pH(W.tools),skills:pH(W.skills),providerId:W.providerId,modelId:W.modelId,maxIterations:W.maxIterations,systemPrompt:j,path:f.path}}function x2($){let f=$.searchPaths??iN($.workspaceRoot),J=new Map,Q=[];for(let W of f.filter(Boolean)){if(!uN(W))continue;let j;try{j=dN(W,{withFileTypes:!0})}catch(X){Q.push({path:W,error:X instanceof Error?X:Error(String(X))});continue}for(let X of j){if(!X.isFile()||!sN(X.name))continue;let Y=rN(W,X.name);try{let V=lN(Y,"utf8"),B=Z6(V,{path:Y}),H=aN(B.name);if(!J.has(H))J.set(H,B)}catch(V){Q.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(J.values()).sort((W,j)=>(W.path?lH(W.path):W.name).localeCompare(j.path?lH(j.path):j.name)),errors:Q}}import{createTool as tN,zodToJsonSchema as oN}from"@cline/shared";import{z as nH}from"zod";var k7="subagent_",o5=64,eN=nH.object({prompt:nH.string().trim().min(1).describe("Task for the subagent to perform")});function $q($){let f="",J=!0;for(let Q of $.trim().toLowerCase()){let Z=Q.charCodeAt(0);if(!(Z>=97&&Z<=122||Z>=48&&Z<=57||Q==="_")||Q==="_"){if(!J)f+="_",J=!0;continue}f+=Q,J=!1}return J?f.slice(0,-1):f}function fq($){let f=2166136261;for(let J=0;J<$.length;J++)f^=$.charCodeAt(J),f=Math.imul(f,16777619);return(f>>>0).toString(36)}function W6($){let f=$q($)||"agent",J=fq($).slice(0,6),Q=`${k7}${f}`;if(Q.length<=o5)return Q;let Z=o5-k7.length-J.length-1,W=f.slice(0,Math.max(1,Z));return`${k7}${W}_${J}`.slice(0,o5)}function j6($){let f=new Set,J=[];for(let Q of[...$].sort((Z,W)=>Z.name.localeCompare(W.name))){let Z=W6(Q.name),W=Z,j=2;while(f.has(W)){let X=`_${j++}`,Y=Math.max(1,o5-X.length);W=`${Z.slice(0,Y)}${X}`}f.add(W),J.push({toolName:W,config:Q})}return J}function Jq($,f){return{...$,providerId:f.providerId??$.providerId,modelId:f.modelId??$.modelId,maxIterations:f.maxIterations??$.maxIterations}}function g2($){return j6($.agents).map(({toolName:f,config:J})=>{return tN({name:f,description:`Use the "${J.name}" subagent: ${J.description}`,inputSchema:oN(eN),execute:async(Z,W)=>{let j=$.configProvider.getRuntimeConfig(),X=V$(Jq(j,J)),Y=$.createSubAgentTools?await $.createSubAgentTools(J,Z,W):[],V=B$({kind:"subagent",prompt:J.systemPrompt,configProvider:X,tools:Y,maxIterations:J.maxIterations,parentAgentId:W.agentId,abortSignal:W.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),B=V.getAgentId(),H=V.getConversationId(),A=W.agentId,K={systemPrompt:J.systemPrompt,task:Z.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:B,conversationId:H,parentAgentId:A,input:K})}catch{}try{let G=await V.run(Z.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:H,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:H,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function R1(){return new Date().toISOString()}function aH($,f){if(f<=0)return 0;return Math.round($/f*100)}function Qq($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let W of Z.requiredSections)if(!J.has(`${Z.id}:${W}`))Q.add(`${Z.id}:${W}`)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function m2($,f){let J={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},W={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")X+=1;else Y+=1;let V=[],B=[],H=f.tasks.filter((P)=>P.status==="completed").length,A=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(Q[P.status]+=1,P.status==="blocked"){V.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((D)=>{return A.get(D)?.status==="completed"}))B.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let F=P.startedAt.getTime();if(F>=R)R=F,G=P.id}for(let P of f.outcomes)W[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:R1(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:Y},tasks:{total:f.tasks.length,byStatus:Q,blockedTaskIds:V,readyTaskIds:B,completionPct:aH(H,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:W,finalizedPct:aH(W.finalized,f.outcomes.length),missingRequiredSections:Qq(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function v2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.task.id,agentId:f.task.assignee??f.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:R1()}}import{sanitizeFileName as Zq,TeamMessageType as I}from"@cline/shared";import{nanoid as Wq}from"nanoid";import{TeamMessageType as Wu}from"@cline/shared";function I7($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function sH($,f){return $?.status==="stopped"&&I7(f)}var jq=600000,tH="recovered_queued";function Xq($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
|
|
497
505
|
|
|
498
|
-
${
|
|
499
|
-
${
|
|
506
|
+
${$.message}`}class u2{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,Q]of Object.entries($))this.addAgent(J,Q)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:I.AgentEvent,agentId:$,event:Z})}},Q=new Y$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set($,Q),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:f});try{let Q=await J.run(f);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:f});try{let Q=await J.continue(f);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async runParallel($){let f=$.map(async(J)=>{let Q=this.agents.get(J.agentId);if(!Q)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:I.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);return this.emitEvent({type:I.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:I.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),{agentId:J.agentId,result:void 0,error:W,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let Q=this.agents.get(J.agentId);if(!Q){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:I.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);this.emitEvent({type:I.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:I.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return f}async runPipeline($,f,J){let Q=[],Z=f;for(let W of $){let j=this.agents.get(W);if(!j){Q.push({agentId:W,result:void 0,error:Error(`Agent "${W}" not found in team`)});break}this.emitEvent({type:I.TaskStart,agentId:W,message:Z});try{let X=await j.run(Z);this.emitEvent({type:I.TaskEnd,agentId:W,result:X}),Q.push({agentId:W,result:X});let Y=$.indexOf(W)+1;if(Y<$.length){let V=$[Y];Z=J?J(X,V):`Previous agent output:
|
|
507
|
+
${X.text}
|
|
500
508
|
|
|
501
|
-
Please continue from here.`}}catch(
|
|
509
|
+
Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:I.TaskEnd,agentId:W,error:Y,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:Y});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function x7($,f){return new u2($,f)}function eH($){let f=x7({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(Q)=>{let Z=await f.routeTo("worker",Q),W=await f.routeTo("reviewer",`Please review this work:
|
|
502
510
|
|
|
503
|
-
${Z.text}`);return{workerResult:Z,reviewResult:W}},J}class
|
|
511
|
+
${Z.text}`);return{workerResult:Z,reviewResult:W}},J}class Of{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${Zq(Wq(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,Q=f?.markRead??!0,Z=f?.limit,W=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let X=new Date;for(let Y of j)if(!Y.readAt)Y.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,c2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,c2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,c2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,c2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,c2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,c2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...f,apiTimeoutMs:jq,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:I.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new Y$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,W),this.emitEvent({type:I.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:W.agentId,role:W.role,description:W.description,status:W.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(Q){if(!I7(Q))throw Q}J.status="stopped",this.emitEvent({type:I.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,Q),this.emitEvent({type:I.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:I.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:I.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...Q}}completeTask($,f,J){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=f;return this.emitEvent({type:I.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...Q}}async routeToTeammate($,f,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:I.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
|
|
504
512
|
|
|
505
|
-
${$}`:$,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:k.TaskEnd,agentId:f,result:j}),this.recordProgressStep(f,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:k.TaskEnd,agentId:f,error:W,messages:Q.agent.getMessages()}),!UV(Q,W))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get(f)?.status!=="stopped")Q.status="idle"}}startTeammateRun(f,$,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,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(Q,Z),this.runQueue.push(Q),this.emitEvent({type:k.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}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[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>$)$=W.priority,f=Z}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===RV;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:k.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let Q=$?$N(f):f.message,Z=await this.routeToTeammate(f.agentId,Q,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=Z,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:k.RunCompleted,run:{...f}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");f.error=Z,f.endedAt=new Date;let W=this.members.get(f.agentId);if(UV(W,Q))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:k.RunCancelled,run:{...f},reason:Z});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:k.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 DV($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await DV(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 Q=this.runQueue.indexOf(f);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:k.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 Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:k.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=f,J.currentActivity=RV,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:k.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:k.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,Q,Z){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let W=this.members.get($);if(!W)throw Error(`Unknown recipient "${$}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:k.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast(f,$,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===f)continue;if(W.role==="lead")continue;Z.push(this.sendMessage(f,W.agentId,$,J,Q?.taskId))}return Z}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:k.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:k.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:k.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:k.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 Q of $.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:k.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(!GW($))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 Q of this.runs.values()){if(Q.agentId!==f||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:k.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${Q}`}recordProgressStep(f,$,J,Q=!1){this.missionStepCounter++;let Z=this.members.get(f);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId: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(`
|
|
506
|
-
`)}emitEvent(
|
|
513
|
+
${f}`:f,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:I.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:I.TaskEnd,agentId:$,error:W,messages:Q.agent.getMessages()}),!sH(Q,W))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,f,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:I.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>f)f=W.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===tH;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:I.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=f?Xq($):$.message,Z=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:I.RunCompleted,run:{...$}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=Z,$.endedAt=new Date;let W=this.members.get($.agentId);if(sH(W,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:I.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:I.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await oH(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await oH($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:I.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:I.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=tH,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:I.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:I.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,Q,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let W=this.members.get(f);if(!W)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:I.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===$)continue;if(W.role==="lead")continue;Z.push(this.sendMessage($,W.agentId,f,J,Q?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:I.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:I.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:I.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:I.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let Q of f.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:I.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!I7(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:I.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${Q}`}recordProgressStep($,f,J,Q=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
|
|
514
|
+
`)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function oH($){return new Promise((f)=>setTimeout(f,$))}function c2($,f){let J=0;for(let Q of $){if(!Q.startsWith(f))continue;let Z=Number.parseInt(Q.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function g7($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),e5($);break}default:break}}async function m7($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let Q=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await J("onTeamTaskProgress",$,f.agentId,Q,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function v7($,f,J,Q){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:v2({teamName:Z,sessionId:f,event:J}),summary:m2(Z,$.runtime.teamRuntime.exportState())}})}function X6($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function c7($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&X6($)}function e5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function u7($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function d7($,f){let J=f.map((W)=>{let j=[`- ${W.runId} (${W.agentId}) -> ${W.status}`];if(W.taskId)j.push(` task=${W.taskId}`);if(typeof W.iterations==="number")j.push(` iterations=${W.iterations}`);if(W.error)j.push(` error=${W.error}`);return j.join("")}),Q=$.activeTeamRunIds.size,Z=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return Y6(`System-delivered teammate async run updates:
|
|
507
515
|
${J.join(`
|
|
508
516
|
`)}
|
|
509
517
|
|
|
510
|
-
${Z}
|
|
511
|
-
`,"utf8"),
|
|
518
|
+
${Z}`,$.config.mode)}function Y6($,f){return Yq($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var l7=4;class i1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new h7($,f.messagesArtifactUploader,f.logger),this.teamChildren=new t5($,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),i1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?_J(f.messages,f,J):LJ($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??e(),J=$.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${Bq(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=t8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:A$(X.metadata),hookPath:"",messagesPath:Z,updatedAt:e()}),this.manifestStore.initializeMessagesFile(Q,Z,f),this.manifestStore.writeSessionManifest(W,X),{manifestPath:W,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let Q;if((await KY(()=>this.adapter.getSession($),async(W)=>{return Q=W0(f)?void 0:e(),this.adapter.updateSession({sessionId:$,status:f,endedAt:Q??null,exitCode:W0(f)?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},l7)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let f=0;f<l7;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=$.metadata!==void 0?A$($.metadata)??{}:A$(Q)??{},W=a$(typeof Q?.title==="string"?Q.title:void 0),j=$.title!==void 0?a$($.title):W??aQ($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:V,manifest:B}=this.manifestStore.readManifestFile($.sessionId);if(B){if($.prompt!==void 0)B.prompt=$.prompt??void 0;let H=$.metadata!==void 0?A$($.metadata)??{}:A$(B.metadata)??{};if(j)H.title=j;B.metadata=Object.keys(H).length>0?H:void 0,this.manifestStore.writeSessionManifest(V,B)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let Q=LJ(f);return this.manifestStore.persistSessionMessages($,Q,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,Q,Z,W){return this.teamChildren.onTeamTaskEnd($,f,J,Q,Z,W)}onTeamTaskProgress($,f,J,Q){return this.teamChildren.onTeamTaskProgress($,f,J,Q)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(W0($.status)===!1||this.isPidAlive($.pid))return $;let f=e(),J=i1.STALE_REASON;for(let Q=0;Q<l7;Q++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(W0(Z.status)===!1)return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:i1.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=AY(Z,{status:"failed",endedAt:f,exitCode:1,metadata:W}),{path:Y}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,i1.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let W=A$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=a$(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),Y=X?{...W??{},title:X}:W;return{...Z,metadata:Y}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),Q=0;for(let Z of J){let W=await this.reconcileDeadRunningSession(Z);if(W&&W.status!==Z.status)Q++}return Q}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(Q.map(async(Z)=>{await DZ(Z.cwd,Z.sessionId),R4(Z.messagesPath),R4(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await DZ(J.cwd,f),R4(J.messagesPath),R4(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(Vq(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function r7(){return new Date().toISOString()}function QA($,f){let J=`${$}.tmp`;Kq(J,`${JSON.stringify(f,null,2)}
|
|
519
|
+
`,"utf8"),Aq(J,$)}class ZA{sessionsDirPath;constructor($=Gq()){this.sessionsDirPath=$}ensureSessionsDir(){if(!p7(this.sessionsDirPath))Hq(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return JA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return JA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!p7($))return{version:1,sessions:{}};try{let f=JSON.parse(fA($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){QA(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!p7($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(fA($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){QA(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:r7()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:r7()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=r7(),this.writeQueue(J),Q.task}}class i7 extends i1{constructor($,f={}){super(new ZA($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}var XA={};w(XA,{CoreSessionService:()=>U1});import{existsSync as Fq,mkdirSync as Pq}from"node:fs";import{resolveSessionDataDir as Dq}from"@cline/shared/storage";var n7=`
|
|
512
520
|
session_id AS sessionId,
|
|
513
521
|
source,
|
|
514
522
|
pid,
|
|
@@ -535,55 +543,56 @@ ${Z}`,f.config.mode)}function f4(f,$){return JN(f,$==="plan"?"plan":$==="yolo"?"
|
|
|
535
543
|
metadata_json AS metadata,
|
|
536
544
|
hook_path AS hookPath,
|
|
537
545
|
messages_path AS messagesPath,
|
|
538
|
-
updated_at AS updatedAt`;function
|
|
546
|
+
updated_at AS updatedAt`;function a7($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let f=$.metadata;if(typeof f==="string"&&f.trim())try{let J=JSON.parse(f);$.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{$.metadata=null}else $.metadata=null;return $}function s7($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function WA($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class jA{store;sessionsDirPath;constructor($,f=Dq()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!Fq(this.sessionsDirPath))Pq(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
539
547
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
540
548
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
541
549
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
542
550
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
543
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
551
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,s7($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${n7} FROM sessions WHERE session_id = ?`,[$]);return f?a7(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${n7}
|
|
544
552
|
FROM sessions
|
|
545
553
|
${Q}
|
|
546
554
|
ORDER BY started_at DESC
|
|
547
|
-
LIMIT ?`,[...J
|
|
555
|
+
LIMIT ?`,[...J,$.limit]).map(a7)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
|
|
548
556
|
SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
|
|
549
557
|
parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
|
|
550
558
|
prompt = COALESCE(prompt, ?)
|
|
551
|
-
WHERE session_id = ? AND status_lock = ?`,[
|
|
552
|
-
VALUES (?, ?, ?, ?, ?, NULL)`,[
|
|
559
|
+
WHERE session_id = ? AND status_lock = ?`,[e(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(s7($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(Q);f.push("updated_at = ?"),J.push(e());let Z=`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`;if(J.push($.sessionId),$.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push($.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
|
|
560
|
+
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,e()])}async claimSpawnRequest($,f){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
|
|
553
561
|
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
554
|
-
ORDER BY id ASC LIMIT 1`,[f
|
|
562
|
+
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 = ?",[e(),J.id]),J.task??void 0}}class U1 extends i1{store;constructor($,f={}){super(new jA($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
555
563
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
556
564
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
557
565
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
558
566
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
559
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
560
|
-
`).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:$;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function DN(f,$){let J=f instanceof Error?f:Error(String(f)),Q=J,Z=$.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function LN(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end($,(j)=>{if(J.off("error",W),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function k2(f,$){let J=FN($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!$.detached,Z=GN(J[0],J.slice(1),{cwd:$.cwd,env:UN($.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(P)=>{K(DN(P,J))})});if(await LN(Z,JSON.stringify(f)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",A=!1,Y;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if(($.timeoutMs??0)>0)Y=setTimeout(()=>{A=!0,Z.kill("SIGKILL")},$.timeoutMs);Z.once("close",(K)=>{if(Y)clearTimeout(Y);let{parsedJson:P,parseError:R}=RN(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:P,parseError:R,timedOut:A})})});return await Promise.race([V,j])}var ON=T1.object({contextModification:T1.string().optional(),cancel:T1.boolean().optional(),review:T1.boolean().optional(),errorMessage:T1.string().optional(),context:T1.string().optional(),overrideInput:T1.unknown().optional()}).passthrough();var TN=["agent","hook"];async function x2(f,$={}){let J=$.command??TN;return await k2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function IV(f){return f instanceof Error?f:Error(String(f))}function zN(f){if(!f||typeof f!=="object")return;let $=ON.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 Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function kV(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,Q]of Object.entries(f))if(typeof Q==="string")$[J]=Q;else $[J]=JSON.stringify(Q);return $}function rf(f,$,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:_N(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function MN(f){return{name:f.name,message:f.message,stack:f.stack}}function NN(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function qN(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function yN(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function wN(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 CN(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 z1(f,$){try{let J=await x2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(IV(J),f)}}function d5(f={}){return{hooks:{beforeRun:async(H)=>{let X=qN(H);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let Y={...rf("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await z1(Y,f)}else{let Y={...rf("agent_start",X,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await z1(Y,f)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...rf("tool_call",X,f),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:kV(H.input)}};try{let Y=await x2(A,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:A,result:Y,detached:!1}),Y?.timedOut)throw Error("tool_call hook command timed out");if(Y?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${Y.parseError}`);return CN(zN(Y?.parsedJson))}catch(Y){f.onDispatchError?.(IV(Y),A);return}},afterTool:async(H)=>{let X=wN(H),A={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...rf("tool_result",A,f),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:kV(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await z1(Y,f);return},afterRun:async({snapshot:H,result:X})=>{let A={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...rf("agent_end",A,f),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await z1(B,f);return}let Y=X.status==="aborted"||NN(X.error?.message)?"agent_abort":"agent_error",V=Y==="agent_error"?{...rf(Y,A,f),hookName:Y,iteration:X.iterations,error:MN(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...rf(Y,A,f),hookName:Y,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await z1(V,f)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...rf("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:yN(H.message.content),attachments:[]}};await z1(A,f)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:A,reason:Y})=>{let V={...rf("session_shutdown",{agentId:H,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:Y};await z1(V,f)}}}var vB={};q(vB,{writeHubDiscovery:()=>w5,withHubStartupLock:()=>C5,verifyHubConnection:()=>Kf,truncateNotificationBody:()=>H4,toHubHealthUrl:()=>oZ,stopLocalHubServerGracefully:()=>YW,startHubWebSocketServer:()=>q1,startHubServer:()=>mB,spawnDetachedHubServerWithRetry:()=>z2,spawnDetachedHubServer:()=>ZW,sendHubCommand:()=>uV,restartLocalHubIfIdleAfterStartupTimeout:()=>h5,resolveWorkspaceHubOwnerContext:()=>kY,resolveSharedHubOwnerContext:()=>A0,resolveHubUrl:()=>kW,resolveHubOwnerContext:()=>uf,resolveHubEndpointOptions:()=>r0,resolveHubBuildId:()=>z$,resolveDefaultHubPort:()=>T2,resolveDefaultHubPathname:()=>QW,resolveDefaultHubHost:()=>JW,resolveCompatibleLocalHubUrl:()=>rJ,resolveClineDir:()=>SY,resolveClineDataDir:()=>uJ,requestHubShutdown:()=>pJ,rememberRecoverableLocalHubUrl:()=>M$,readHubDiscovery:()=>P0,probeHubServer:()=>Bf,probeHubConnection:()=>cV,prewarmDetachedHubServer:()=>S5,normalizeHubWebSocketUrl:()=>N$,isHubReconnectableTransportError:()=>XW,isHubCommandTimeoutError:()=>E5,isDiscoveryFilePresent:()=>hY,ensureHubWebSocketServer:()=>e5,ensureHubServer:()=>gB,ensureDetachedHubServer:()=>xY,ensureCompatibleLocalHubUrl:()=>D1,createLocalHubScheduleRuntimeHandlers:()=>f9,createInMemoryHubOwnerContext:()=>EY,createHubServerUrl:()=>Jf,createHubAuthToken:()=>y5,createConfiguredTelemetryService:()=>nf,createConfiguredTelemetryHandle:()=>u2,connectToHub:()=>i5,clearHubDiscovery:()=>p0,NodeHubClient:()=>Qf,NativeHubTransportAdapter:()=>B4,HubUIClient:()=>mW,HubTransportError:()=>M0,HubSessionClient:()=>xW,HubServerTransport:()=>l2,HubScheduleService:()=>g2,HubScheduleCommandService:()=>m2,HubCommandError:()=>M2,DEFAULT_HUB_PORT:()=>fW,DEFAULT_HUB_PATHNAME:()=>$W,DEFAULT_HUB_HOST:()=>eZ,BrowserWebSocketHubAdapter:()=>V4});import{createSessionId as SN}from"@cline/shared";function i0(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function mV(f,$,J){return{version:f.version,requestId:f.requestId??SN("hubreq_"),ok:!1,error:{code:$,message:J}}}class m2{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return i0(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return i0(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 i0(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return i0(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return i0(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return i0(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return i0(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return i0(f,{execution:f.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String(f.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return i0(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 i0(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return i0(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return i0(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return mV(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return mV(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 p5(f){return f?new Date(f).getTime():void 0}function EN(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function l5(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:p5(f.nextRunAt),lastRunAt:p5(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:EN(f)}}function hN(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function SW(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:p5(f.startedAt),endedAt:p5(f.completedAt),status:hN(f.status),errorMessage:f.error}}class g2{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new xJ({dbPath:f.dbPath}),this.materializer=new EJ({store:this.store}),this.runner=new hJ({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,eventPublisher:f.eventPublisher,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(kZ(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return l5(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?l5($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>l5($))}updateSchedule(f,$){if($.cronPattern!==void 0)kZ($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let Q=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule(f,{...$,scheduleId:f});return W?l5(W):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 SW(J,f)}triggerScheduleNowDetached(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;return this.runner.tick().catch(()=>{return}),SW($,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((Z)=>{let W=$??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return SW(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!f.status||Z.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,Q=0,Z=0,W;for(let j of $){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}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,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}r5();function Jq(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 Qq="cline-hub-auth.";function Zq(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function Wq(f,$){let J=new URL(f),Q=new URL($);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function jq(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=A0(),Q=await P0(J.discoveryPath);if(Q?.url&&Wq(f.toString(),Q.url))return Q.authToken;return}async function kW(f={}){let $=r0(f);if(!Zq(f)){let J=A0(),Q=await P0(J.discoveryPath);if(Q?.url)return Q.url}return Jf($.host,$.port,$.pathname)}async function i5(f){return await new Promise(($,J)=>{(async()=>{let Q=new URL(f),Z=await jq(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${Qq}${Z}`]:void 0),j=new Map,H=0;W.addEventListener("open",()=>{$({send(X){let A=X.requestId??`hub-client-${++H}`;return new Promise((Y,V)=>{j.set(A,{resolve:Y,reject:V});let B={kind:"command",envelope:{...X,requestId:A}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let Y=j.get(A.envelope.requestId);if(Y)j.delete(A.envelope.requestId),Y.resolve(A.envelope)}}),W.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(X)=>{J(Jq(X,f))})})().catch(J)})}async function cV(f){try{return(await i5(f)).close(),!0}catch{return!1}}async function uV(f,$){let J=await kW(f),Q=await i5(J);try{return await Q.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{Q.close()}}function IW(f){return f?JSON.parse(JSON.stringify(f)):{}}function n5(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?IW($.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 dV(f,$){return f.error?.message??`hub command failed: ${$}`}function Hq(f){let $=IW(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 Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...$,error:Q.message.trim()};return $}function lV(f){let $=f?.sessionId;return typeof $==="string"&&$.trim()?$.trim():void 0}function Xq(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 Aq(f){let $=IW(f.payload);if(f.event==="schedule.execution_completed")return{sessionId:f.sessionId?.trim()||lV($)||"",eventType:"schedule.execution.completed",payload:$};if(f.event==="schedule.execution_failed")return{sessionId:f.sessionId?.trim()||lV($)||"",eventType:"schedule.execution.failed",payload:$};let J=f.sessionId?.trim();if(!J)return;switch(f.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:$};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:$};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:$};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:$};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:$};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:$};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:$};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:$};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:Hq(f.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:$};default:return}}class xW{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new Qf({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=n5($.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,mode:$.config.mode,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 $;try{$=await this.client.command("session.get",void 0,f)}catch(J){if(cf(J))return;throw J}return n5($.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(dV(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}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 Q=f.config,Z=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},$);if(!Z.ok)throw Error(dV(Z,"session.restore"));let W=n5(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,H=Xq(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}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((Q)=>n5({session:Q})).filter((Q)=>Boolean(Q?.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((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=Aq(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;$.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{$.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress(f,$){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;$.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{$.onError?.(Q instanceof Error?Q:Error(String(Q)))}),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 mW{client;constructor(f){this.client=new Qf({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}function Yq(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(`
|
|
561
|
-
`).trim()||void 0}var pV=120,gW="...";function H4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=pV)return $;let J=pV-Buffer.byteLength(gW,"utf8");if(J<=0)return gW;let Q="";for(let Z of $){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${gW}`}async function rV(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,Z=[...await T$(J)].reverse().find((X)=>X.role==="assistant"),W=Z?Yq(Z.content):void 0,j=f?.workspaceRoot?.trim()||"workspace",H=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():j;return{title:`Task completed (${$})`,body:H4(W&&W.length>0?W:H.length>0?H:j),severity:"info"}}import{captureSdkError as o5,createSessionId as dq}from"@cline/shared";import{createSessionId as Pq}from"@cline/shared";import{createSessionId as Kq}from"@cline/shared";function Vq(f){switch(f){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Bq(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 a5(f,$,J,Q){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:Vq(f.status),participants:$?[...$.participants.values()]:[],metadata:Bq(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}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function d(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function v(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function t5(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function E0(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function M1(f,$,J){return{version:"v1",event:f,eventId:Kq("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function n0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let Q=await f.sessionHost.getAccumulatedUsage?.($);return a5(J,f.sessionState.get($),Q?.usage,Q?.aggregateUsage)}async function a0(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[Q,Z]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return Pf({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function s5(f,$,J,Q,Z={}){let W=f.sessionState.get($);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return f.sessionState.set($,j),j}async function vW(f,$){let J=Pq("approval_"),Q=$.sessionId;if(f.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{f.pendingApprovals.set(J,{sessionId:Q,resolve:W}),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},Q))})}function cW(f,$,J){let Q=f.pendingApprovals.get($);if(!Q)return;return f.pendingApprovals.delete($),Q.resolve(J),{sessionId:Q.sessionId}}function uW(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingApprovals.entries()]){if(!$({approvalId:Z,sessionId:W.sessionId}))continue;f.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function iV(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return v($,"approval_not_found",`Unknown approval: ${J}`);let Z=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,W=$.payload?.approved===!0,j=cW(f,J,{approved:W,reason:Z});if(!j)return v($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),d($,{approvalId:J,approved:W})}import{createSessionId as Uq}from"@cline/shared";function Gq(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var nV={debug:10,info:20,warn:30,error:40,silent:50};function Fq(){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 c(f,$,J={}){if(nV[f]<nV[Fq()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,Gq(W)]).filter(([,Z])=>Z!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function dW(f,$){let J=$ instanceof Error?$.stack||$.message:String($);c("error",f,{error:J})}async function aV(f,$,J,Q,Z,W){let j=Uq("capreq_"),H=performance.now();return c("info","capability.request.start",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z}),await new Promise((X,A)=>{f.pendingCapabilityRequests.set(j,{sessionId:$,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(Y)=>{if(c(Y.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z,ok:Y.ok,error:Y.error,durationMs:Math.round(performance.now()-H)}),!Y.ok){A(Error(Y.error||`Capability ${J} was rejected by ${Z}.`));return}X(Y.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},$)),c("info","capability.request.published",{requestId:j,sessionId:$,capabilityName:J,targetClientId:Z})})}function tV(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return v($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==Q.targetClientId)return v($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return v($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return Q.onProgress?.(W),d($,{requestId:J})}function w$(f,$,J){let Q=0;for(let[Z,W]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:Z,...W}))continue;f.pendingCapabilityRequests.delete(Z),c("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function sV(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",Q=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!Q||!Z)return v($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=await f.requestCapability(J,Q,W,Z);return d($,j)}catch(W){return v($,"capability_request_failed",W instanceof Error?W.message:String(W))}}function oV(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",Q=f.pendingCapabilityRequests.get(J);if(!Q)return v($,"capability_not_found",`Unknown capability request: ${J}`);let Z=$.clientId?.trim()||"";if(Z!==Q.targetClientId)return v($,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==Q.sessionId)return v($,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);f.pendingCapabilityRequests.delete(J);let W=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,j=typeof $.payload?.error==="string"?$.payload.error:void 0,H=$.payload?.ok===!0;return c(H?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,error:j}),Q.resolve({ok:H,payload:W,error:j}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:H,payload:W,error:j},Q.sessionId)),d($,{requestId:J,ok:H})}import{createSessionId as Rq}from"@cline/shared";function eV(f,$){let J=$.payload,Q=J?.clientId?.trim()||$.clientId?.trim()||Rq("client_");return f.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),d($,{clientId:Q})}function fB(f,$){let J=$.clientId?.trim(),Q=J?f.clients.get(J):void 0;if(!J||!Q)return v($,"client_not_found","Client is not registered with this hub.");let Z=t5($.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return d($)}function $B(f,$,J){let Q=$.clientId?.trim();if(Q)f.clients.delete(Q),J(Q),f.publish(f.buildEvent("hub.client.disconnected",{clientId:Q}));return d($)}function JB(f,$){return d($,{clients:[...f.clients.values()]})}var Dq=30000;function Lq(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function _q(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function Oq(f,$,J){let Q=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${$}`;return v(f,P1,Q)}function Tq(f){return f?f:void 0}function zq(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 Mq(f,$,J,Q){let Z=performance.now(),W=!1,j={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:Q},H=setInterval(()=>{if(W)return;let Y=Math.round(performance.now()-Z);c("warn","run.heartbeat",{...j,elapsedMs:Y}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:Y,...Q?{timeoutMs:Q}:{}},J.sessionId))},Dq),X=f.sessionHost.runTurn(J);X.then((Y)=>{if(!W)return;c("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:Y?.finishReason})},(Y)=>{if(!W)return;c("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:Y})});let A;try{if(!Q)return await X;return await Promise.race([X,new Promise((Y,V)=>{A=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${Q}ms.`;W=!0,clearInterval(H),V(Error(B)),c("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),uW(f,(K)=>K.sessionId===J.sessionId,B),w$(f,(K)=>K.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((K)=>{c("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(H),A)clearTimeout(A)}}async function QB(f,$){let J=E0($),Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return v($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((Y)=>typeof Y==="string"):void 0,H=zq(Q);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await Mq(f,$,{sessionId:J,prompt:Z,mode:Tq(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:H},H)}catch(Y){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);if(cf(Y))return Oq($,J,Y);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:Y instanceof Error?Y.message:String(Y)},J)),Y}if(X){let Y=await a0(f,J),V=_q(X);if(f.publish(f.buildEvent(Lq(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...Y?{snapshot:Y}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let A=await a0(f,J);return d($,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function ZB(f,$){let J=E0($),Q=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";uW(f,(Z)=>Z.sessionId===J,Q);try{await f.sessionHost.abort(J,$.payload?.reason)}catch(Z){c("warn","run.abort_failed",{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J,error:Z})}finally{w$(f,(Z)=>Z.sessionId===J,Q)}return d($,{applied:!0})}async function WB(f,$){let J=I2($.payload?.payload);if(!J)return v($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),d($,{applied:!0})}async function jB(f,$){switch($.type){case"chunk":return;case"agent_event":await Nq(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,Q]=await Promise.all([n0(f,$.payload.sessionId),a0(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},$.payload.sessionId));return}case"ended":await qq(f,$);return;default:return}}async function Nq(f,$){let{sessionId:J,event:Q}=$.payload;if(Q.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await f.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}f.publish(f.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:$.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:$.payload.teamAgentId,teamRole:$.payload.teamRole}},J));return}if(Q.type==="done")f.publish(f.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function qq(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),Q=J===$.payload.reason||J==="run.start.reply";if(Q)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[Z,W]=await Promise.all([n0(f,$.payload.sessionId),a0(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let j=await rV(Z);f.publish(f.buildEvent("ui.notify",j,$.payload.sessionId))}if(Q)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...W?{snapshot:W}:{}},$.payload.sessionId))}import{createSessionId as KB,parseRuntimeConfigExtensions as PB}from"@cline/shared";var YB={};q(YB,{SessionVersioningService:()=>C$,SessionVersioningError:()=>h0});var AB={};q(AB,{trimMessagesToCheckpoint:()=>XB,trimMessagesBeforeCheckpoint:()=>pW,readSessionCheckpointHistory:()=>X4,createRestoredCheckpointMetadata:()=>lW,createCheckpointRestorePlan:()=>rW,applyCheckpointToWorktree:()=>iW});import{execFile as yq}from"node:child_process";import{promisify as wq}from"node:util";var d2=wq(yq);function X4(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((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let H=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...H?{kind:H}:{}}]})}function lW(f,$){let J=X4(f).filter((Z)=>Z.runCount<=$),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function Cq(f,$){return f.reduce((J,Q)=>{if(Q.runCount>$)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function HB(f,$){let J=0;for(let Q=0;Q<f.length;Q+=1){let Z=f[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return Q}throw Error(`Could not find user message for checkpoint run ${$}`)}function XB(f,$){let J=HB(f,$);return f.slice(0,J+1)}function pW(f,$){let J=HB(f,$);return f.slice(0,J)}function rW(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=Cq(X4(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let Q=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...f.restoreMessages!==!1?{messages:XB(f.messages??[],$)}:{}}}async function iW(f,$){if((await d2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await d2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await d2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await d2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await d2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await d2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class h0 extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function Sq(f){let $=f.sessionId.trim();if(!$)throw new h0("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new h0("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new h0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new h0("invalid_restore","checkpointRunCount must be a positive integer");return $}class C${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,Q=Sq({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),Z=await f.getSession(Q);if(!Z)throw new h0("session_not_found",`Session ${Q} not found`);let W=$?await f.readMessages(Q):void 0;if($&&W?.length===0)throw new h0("session_messages_not_found",`No messages found for session ${Q}`);let j=rW({session:Z,messages:W,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??iW)(j.cwd,j.checkpoint);let H=Pf({session:Z,messages:W});if(!$)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=lW(Z,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?pW(W??[],f.checkpointRunCount):j.messages??[],Y={sourceSession:Z,sourceMessages:W,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new h0("invalid_restore","start is required when restore.messages is true");let V=f.buildStartInput?await f.buildStartInput(Y,f.start):f.start,B=await f.startSession(V),K=f.getStartedSessionId?.(B);if(K)await(f.retainCheckpointRefs??LX)(j.cwd,K,X?.history??[]);let P=K&&f.readRestoredSession?await f.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...P?{restoredSnapshot:Pf({session:P,messages:A})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as Jd,HUB_COMPACTION_CAPABILITY as Qd,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Zd,HUB_HOOK_CAPABILITY_PREFIX as Wd,HUB_MISTAKE_LIMIT_CAPABILITY as jd,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Hd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Xd,isHubToolExecutorName as Eq}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Kd,HUB_COMPACTION_CAPABILITY as Pd,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Gd,HUB_HOOK_CAPABILITY_PREFIX as Fd,HUB_MISTAKE_LIMIT_CAPABILITY as Ud,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Rd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Dd}from"@cline/shared";var hq=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function N1(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function bq(f,$){let J=typeof f.name==="string"?f.name.trim():"",Q=typeof f.description==="string"?f.description:"",Z=typeof f.capabilityName==="string"?f.capabilityName.trim():"",W=N1(f.inputSchema);if(!J||!Q||!W||!Z||$.has(Z))return;return $.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...N1(f.lifecycle)?{lifecycle:N1(f.lifecycle)}:{}}}function aW(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let Q of f){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let H=bq(Z,J);if(H)$.push(H);continue}if(W==="toolExecutor"){let H=Z.executor;if(!Eq(H))continue;J.add(j),$.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(W==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),$.push({kind:"hook",capabilityName:j,name:H});continue}if(W==="compaction"){J.add(j),$.push({kind:"compaction",capabilityName:j,...N1(Z.config)?{config:N1(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),$.push({kind:"checkpoint",capabilityName:j,...N1(Z.config)?{config:N1(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),$.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),$.push({kind:"userInstructionService",capabilityName:j})}return $}function BB(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function kq(f){return Object.hasOwn(f,"update")?f.update:f}function A4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function Iq(f){let $=(f??[]).map(A4).filter(Boolean);return $.length>0?new Set($):void 0}function xq(f,$,J){if(!J)return!0;let Q=A4(f),Z=A4($),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function nW(f,$){let J=Iq($);return f.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>xq(Q.id,Q.name,J))}function VB(f,$){let J=async(Q,Z)=>{let W=A4(Q),H=nW(f,$).filter((B)=>B.id===W||A4(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${Q}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let X=H[0].skill,A=Z?.trim(),Y=A?`
|
|
562
|
-
<command-args>${A}</command-args>`:"",V=X.description?.trim()?`Description: ${X.description.trim()}
|
|
567
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,e()])}}function Rq($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var V6,B6;function Uq($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;l5(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function zq($){await $.reconcileDeadSessions?.().catch(()=>{})}function BA($){try{let f=new D1;return f.init(),new U1(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),VA($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new i7(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function YA($,f,J){return new z1({sessionService:J??$.sessionService??BA($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function t7($){if(V6)return V6;if(B6)return await B6;return B6=(async()=>{return V6=BA($),await zq(V6),V6})().finally(()=>{B6=void 0}),await B6}async function d2($){let f=h0($.distinctId);$.telemetry?.setDistinctId(f);let J=Rq($);if(Uq(J,$),J==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new k2({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let Q=$.hub?.endpoint?.trim(),Z=Q||await Lf({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new p1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let Q=await $6({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new p1({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(W){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),VA($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),YA($,f)}return YA($,f)}var GA={};w(GA,{NoOpFeatureFlagsProvider:()=>Tf,FeatureFlagsService:()=>Mf});import{existsSync as Lq,mkdirSync as _q,readFileSync as Oq,writeFileSync as Mq}from"node:fs";import{dirname as Tq}from"node:path";import{FEATURE_FLAGS as AA,FeatureFlagDefaultValue as o7}from"@cline/shared";var Nq=3600000,qq=604800000,KA=1;class Mf{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Nq,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??qq,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let f=$??this.context.userId??null,J=Date.now();if(J-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===f)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:J,userId:f||null};try{let Z=await this.provider.getAllFlagsAndPayloads({flagKeys:AA.length>0?AA:void 0,context:{...this.context,userId:f}});if(this.cacheInfo.userId!==f)return;this.cacheInfo.flagsPayload=Z,this.rebuildCacheFromSnapshot(Z),this.writePersistentCache()}catch(Z){if(this.cacheInfo.userId!==f)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:Z}),Z}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((f)=>this.isFeatureFlagPayload(f));if(typeof $==="object")return Object.values($).every((f)=>this.isFeatureFlagPayload(f));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(f.length===0)return;let J={};for(let[Q,Z]of f)J[Q]=Z;return J}readPersistentCache(){try{if(!this.cacheFilePath||!Lq(this.cacheFilePath))return;let $=JSON.parse(Oq(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let f=$;if(f.version!==KA||typeof f.updatedAt!=="number"||!Number.isFinite(f.updatedAt)||Date.now()-f.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:f.updatedAt,userId:f.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(f.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(f.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;_q(Tq(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),f={version:KA,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};Mq(this.cacheFilePath,`${JSON.stringify(f,null,2)}
|
|
568
|
+
`,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let f=new Map;for(let J of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(J);f.set(J,Q??!1)}this.cache=f}getFeatureFlag($){try{let f=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],J=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=f??J??o7[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:x.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:J}});return Q}catch(f){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:f}),o7[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??o7[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,f){if(process.env.IS_TEST==="true")this.cache.set($,f)}async dispose(){await this.provider.dispose()}}class Tf{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}I2();class H6{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,Q,Z,W,j,X,Y,V){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=X,this.featureFlags=Y,this.settings=LB($),this.pendingPrompts=_B($),this.automation=new bZ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new n4({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:CV(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:EV({host:$,getExtensionContext:()=>G5({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((B)=>{if(B.type!=="ended")return;this.disposeSessionBootstrap(B.payload.sessionId)})}static async create($={}){let f=h0($.distinctId),J=U0($.capabilities),Q={...$,capabilities:J,distinctId:f},Z=await d2(Q),W=SV($.automation),j=$.featureFlags||new Mf({provider:new Tf,telemetry:$.telemetry,logger:$.logger,context:{distinctId:f,clientName:$.clientName}}),X=new H6(Z,$.clientName,Z.runtimeAddress,$.prepare,J,$.logger,$.telemetry,f,j,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=MB($),J=await this.prepare?.(f);try{let Q=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(iZ(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>G5({automationService:this.automationService,automation:this.automation,context:W,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return TB({input:Q,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(Q){throw await Promise.resolve(J?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await x5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?iZ($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>G5({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var PA={};w(PA,{resolvePluginSkillDirectoriesFromPaths:()=>$f,resolvePluginConfigSearchPaths:()=>W4,resolveAndLoadAgentPlugins:()=>H2,resolveAgentPluginPaths:()=>e$,loadAgentPluginsFromPathsWithDiagnostics:()=>o$,loadAgentPluginsFromPaths:()=>SJ,loadAgentPluginFromPath:()=>Q4,discoverPluginModulePaths:()=>j4});var UA={};w(UA,{toHookConfigFileName:()=>V4,runSubprocessEvent:()=>l2,runHook:()=>r2,resolveHooksConfigSearchPaths:()=>X4,parseHookEventPayload:()=>p2,mergeAgentHooks:()=>Zf,listHookConfigFiles:()=>F$,createSubprocessHooks:()=>J9,createHookConfigFileHooks:()=>B4,createHookConfigFileExtension:()=>F2,createHookAuditHooks:()=>G2,createAgentHooksExtension:()=>A2,HookEventPayloadSchema:()=>f9,HookEventNameSchema:()=>$9,HookConfigFileName:()=>K2,HOOK_CONFIG_FILE_EVENT_MAP:()=>Y4,HOOKS_CONFIG_DIRECTORY_NAME:()=>xJ});import{HookEventNameSchema as $9,HookEventPayloadSchema as f9,parseHookEventPayload as p2,resolveHookSessionContext as bq}from"@cline/shared";import{z as Nf}from"zod";import{spawn as wq}from"node:child_process";import{augmentNodeCommandForDebug as yq,withResolvedClineBuildEnv as Sq}from"@cline/shared";function Cq($){let f=$.trim();if(!f)return{};let Q=f.split(`
|
|
569
|
+
`).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function Eq($,f){let J=$ instanceof Error?$:Error(String($)),Q=J,Z=f.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function hq($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end(f,(j)=>{if(J.off("error",W),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function l2($,f){let J=yq(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!f.detached,Z=wq(J[0],J.slice(1),{cwd:f.cwd,env:Sq(f.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}A()})}),j=new Promise((A,K)=>{Z.once("error",(G)=>{K(Eq(G,J))})});if(await hq(Z,JSON.stringify($)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,B;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let H=new Promise((A)=>{if((f.timeoutMs??0)>0)B=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(B)clearTimeout(B);let{parsedJson:G,parseError:R}=Cq(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([H,j])}var kq=Nf.object({contextModification:Nf.string().optional(),cancel:Nf.boolean().optional(),review:Nf.boolean().optional(),errorMessage:Nf.string().optional(),context:Nf.string().optional(),overrideInput:Nf.unknown().optional()}).passthrough();var Iq=["agent","hook"];async function r2($,f={}){let J=f.command??Iq;return await l2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function RA($){return $ instanceof Error?$:Error(String($))}function xq($){if(!$||typeof $!=="object")return;let f=kq.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function DA($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))if(typeof Q==="string")f[J]=Q;else f[J]=JSON.stringify(Q);return f}function n1($,f,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:bq(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function gq($){return{name:$.name,message:$.message,stack:$.stack}}function mq($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function vq($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function cq($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function uq($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function dq($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function qf($,f){try{let J=await r2($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(RA(J),$)}}function J9($={}){return{hooks:{beforeRun:async(X)=>{let Y=vq(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let B={...n1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await qf(B,$)}else{let B={...n1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await qf(B,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...n1("tool_call",Y,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:DA(X.input)}};try{let B=await r2(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:B,detached:!1}),B?.timedOut)throw Error("tool_call hook command timed out");if(B?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${B.parseError}`);return dq(xq(B?.parsedJson))}catch(B){$.onDispatchError?.(RA(B),V);return}},afterTool:async(X)=>{let Y=uq(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},B={...n1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:DA(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await qf(B,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={...n1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await qf(A,$);return}let B=Y.status==="aborted"||mq(Y.error?.message)?"agent_abort":"agent_error",H=B==="agent_error"?{...n1(B,V,$),hookName:B,iteration:Y.iterations,error:gq(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...n1(B,V,$),hookName:B,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await qf(H,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...n1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:cq(X.message.content),attachments:[]}};await qf(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:B})=>{let H={...n1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:B};await qf(H,$)}}}var wK={};w(wK,{writeHubDiscovery:()=>v5,withHubStartupLock:()=>c5,verifyHubConnection:()=>G1,truncateNotificationBody:()=>F6,toHubStatusUrl:()=>U7,toHubHealthUrl:()=>u5,stopLocalHubServerGracefully:()=>C7,startHubWebSocketServer:()=>Sf,startHubServer:()=>NK,spawnDetachedHubServerWithRetry:()=>E2,spawnDetachedHubServer:()=>T7,sendHubCommand:()=>TA,restartLocalHubIfIdleAfterStartupTimeout:()=>i5,resolveWorkspaceHubOwnerContext:()=>BH,resolveSharedHubOwnerContext:()=>E0,resolveProductionHubOwnerContext:()=>n0,resolveHubUrl:()=>QW,resolveHubOwnerContext:()=>d1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>m5,resolveDefaultHubPort:()=>C2,resolveDefaultHubPathname:()=>M7,resolveDefaultHubHost:()=>O7,resolveCompatibleLocalHubUrl:()=>$6,resolveClineDir:()=>jH,resolveClineDataDir:()=>Rf,requestHubShutdown:()=>e4,rememberRecoverableLocalHubUrl:()=>T$,readHubDiscovery:()=>H0,readBearerToken:()=>A9,probeHubServer:()=>l1,probeHubConnection:()=>MA,prewarmDetachedHubServer:()=>l5,normalizeHubWebSocketUrl:()=>N$,isHubReconnectableTransportError:()=>y7,isHubCommandTimeoutError:()=>r5,isDiscoveryFilePresent:()=>YH,ensureHubWebSocketServer:()=>K9,ensureHubServer:()=>qK,ensureDetachedHubServer:()=>PH,ensureCompatibleLocalHubUrl:()=>Lf,createLocalHubScheduleRuntimeHandlers:()=>G9,createInMemoryHubOwnerContext:()=>XH,createHubServerUrl:()=>Z1,createHubAuthToken:()=>g5,createConfiguredTelemetryService:()=>a1,createConfiguredTelemetryHandle:()=>t2,connectToHub:()=>j9,clearHubDiscovery:()=>C0,NodeHubClient:()=>W1,NativeHubTransportAdapter:()=>z6,HubUIClient:()=>jW,HubTransportError:()=>T0,HubSessionClient:()=>WW,HubServerTransport:()=>e2,HubScheduleService:()=>n2,HubScheduleCommandService:()=>i2,HubCommandError:()=>h2,DEFAULT_HUB_PORT:()=>L7,DEFAULT_HUB_PATHNAME:()=>_7,DEFAULT_HUB_HOST:()=>z7,BrowserWebSocketHubAdapter:()=>U6});import{createSessionId as lq}from"@cline/shared";function a0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function zA($,f,J){return{version:$.version,requestId:$.requestId??lq("hubreq_"),ok:!1,error:{code:f,message:J}}}class i2{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return a0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return a0($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return a0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return a0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return a0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return a0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return a0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return a0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return a0($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return a0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return a0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return a0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return zA($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return zA($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}function Z9($){return $?new Date($).getTime():void 0}function pq($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function Q9($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:Z9($.nextRunAt),lastRunAt:Z9($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:pq($)}}function rq($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function e7($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:Z9($.startedAt),endedAt:Z9($.completedAt),status:rq($.status),errorMessage:$.error}}class n2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new i4({dbPath:$.dbPath}),this.materializer=new u4({store:this.store}),this.runner=new d4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(J7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return Q9(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?Q9(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>Q9(f))}updateSchedule($,f){if(f.cronPattern!==void 0)J7(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let Q=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule($,{...f,scheduleId:$});return W?Q9(W):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return e7(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),e7(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let W=f??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return e7(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}W9();import{resolveClineBuildEnv as Fw}from"@cline/shared";function Pw($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var Dw="cline-hub-auth.";function Rw($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function Uw($,f){let J=new URL($),Q=new URL(f);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}function OA(){return Fw()==="production"?n0():E0()}async function zw($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=OA(),Q=await H0(J.discoveryPath);if(Q?.url&&Uw($.toString(),Q.url))return Q.authToken;return}async function QW($={}){let f=i0($);if(!Rw($)){let J=OA(),Q=await H0(J.discoveryPath);if(Q?.url)return Q.url}return Z1(f.host,f.port,f.pathname)}async function j9($){return await new Promise((f,J)=>{(async()=>{let Q=new URL($),Z=await zw(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${Dw}${Z}`]:void 0),j=new Map,X=0;W.addEventListener("open",()=>{f({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((B,H)=>{j.set(V,{resolve:B,reject:H});let A={kind:"command",envelope:{...Y,requestId:V}};W.send(JSON.stringify(A))})},close(){W.close()}})}),W.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let B=j.get(V.envelope.requestId);if(B)j.delete(V.envelope.requestId),B.resolve(V.envelope)}}),W.addEventListener("close",()=>{for(let Y of j.values())Y.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(Y)=>{J(Pw(Y,$))})})().catch(J)})}async function MA($){try{return(await j9($)).close(),!0}catch{return!1}}async function TA($,f){let J=await QW($),Q=await j9(J);try{return await Q.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{Q.close()}}function ZW($){return $?JSON.parse(JSON.stringify($)):{}}function X9($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?ZW(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function NA($,f){return $.error?.message??`hub command failed: ${f}`}function Lw($){let f=ZW($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...f,error:Q.message.trim()};return f}function qA($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function _w($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function Ow($){let f=ZW($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||qA(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||qA(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:Lw($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class WW{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new W1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=X9(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(u1(J))return;throw J}return X9(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(NA(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},f);if(!Z.ok)throw Error(NA(Z,"session.restore"));let W=X9(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=_w(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((Q)=>X9({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=Ow(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;f.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress($,f){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;f.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{f.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class jW{client;constructor($){this.client=new W1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{resolveClineBuildEnv as MK}from"@cline/shared";function Mw($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
|
|
570
|
+
`).trim()||void 0}var wA=120,XW="...";function F6($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=wA)return f;let J=wA-Buffer.byteLength(XW,"utf8");if(J<=0)return XW;let Q="";for(let Z of f){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${XW}`}async function yA($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await M$(J)].reverse().find((Y)=>Y.role==="assistant"),W=Z?Mw(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:F6(W&&W.length>0?W:X.length>0?X:j),severity:"info"}}import{captureSdkError as H9,createSessionId as Qy}from"@cline/shared";import{createSessionId as ww}from"@cline/shared";import{createSessionId as qw}from"@cline/shared";function Tw($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Nw($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function Y9($,f,J,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:Tw($.status),participants:f?[...f.participants.values()]:[],metadata:Nw($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function l($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function v($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function V9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function b0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function wf($,f,J){return{version:"v1",event:$,eventId:qw("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function s0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let Q=await $.sessionHost.getAccumulatedUsage?.(f);return Y9(J,$.sessionState.get(f),Q?.usage,Q?.aggregateUsage)}async function t0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[Q,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return F1({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function B9($,f,J,Q,Z={}){let W=$.sessionState.get(f);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(f,j),j}async function YW($,f){let J=ww("approval_"),Q=f.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{$.pendingApprovals.set(J,{sessionId:Q,resolve:W}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},Q))})}function VW($,f,J){let Q=$.pendingApprovals.get(f);if(!Q)return;return $.pendingApprovals.delete(f),Q.resolve(J),{sessionId:Q.sessionId}}function BW($,f,J){let Q=0;for(let[Z,W]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:W.sessionId}))continue;$.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function SA($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return v(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,W=f.payload?.approved===!0,j=VW($,J,{approved:W,reason:Z});if(!j)return v(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),l(f,{approvalId:J,approved:W})}import{createSessionId as Cw}from"@cline/shared";function yw($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var CA={debug:10,info:20,warn:30,error:40,silent:50};function Sw(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function c($,f,J={}){if(CA[$]<CA[Sw()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,yw(W)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function HW($,f){let J=f instanceof Error?f.stack||f.message:String(f);c("error",$,{error:J})}async function EA($,f,J,Q,Z,W){let j=Cw("capreq_"),X=performance.now();return c("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(B)=>{if(c(B.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:B.ok,error:B.error,durationMs:Math.round(performance.now()-X)}),!B.ok){V(Error(B.error||`Capability ${J} was rejected by ${Z}.`));return}Y(B.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},f)),c("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function hA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return v(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==Q.targetClientId)return v(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return v(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return Q.onProgress?.(W),l(f,{requestId:J})}function y$($,f,J){let Q=0;for(let[Z,W]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...W}))continue;$.pendingCapabilityRequests.delete(Z),c("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function bA($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",Q=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!Q||!Z)return v(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,Q,W,Z);return l(f,j)}catch(W){return v(f,"capability_request_failed",W instanceof Error?W.message:String(W))}}function kA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return v(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==Q.targetClientId)return v(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return v(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(J);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return c(X?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,error:j}),Q.resolve({ok:X,payload:W,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,payload:W,error:j},Q.sessionId)),l(f,{requestId:J,ok:X})}import{createSessionId as Ew}from"@cline/shared";function IA($,f){let J=f.payload,Q=J?.clientId?.trim()||f.clientId?.trim()||Ew("client_");return $.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),l(f,{clientId:Q})}function xA($,f){let J=f.clientId?.trim(),Q=J?$.clients.get(J):void 0;if(!J||!Q)return v(f,"client_not_found","Client is not registered with this hub.");let Z=V9(f.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return l(f)}function gA($,f,J){let Q=f.clientId?.trim();if(Q)$.clients.delete(Q),J(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return l(f)}function mA($,f){return l(f,{clients:[...$.clients.values()]})}var hw=30000;function bw($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function kw($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function Iw($,f,J){let Q=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return v($,Gf,Q)}function xw($){return $?$:void 0}function gw($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function mw($,f,J,Q){let Z=performance.now(),W=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:Q},X=setInterval(()=>{if(W)return;let B=Math.round(performance.now()-Z);c("warn","run.heartbeat",{...j,elapsedMs:B}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:B,...Q?{timeoutMs:Q}:{}},J.sessionId))},hw),Y=$.sessionHost.runTurn(J);Y.then((B)=>{if(!W)return;c("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:B?.finishReason})},(B)=>{if(!W)return;c("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:B})});let V;try{if(!Q)return await Y;return await Promise.race([Y,new Promise((B,H)=>{V=setTimeout(()=>{let A=`Hub run ${f.command} timed out after ${Q}ms.`;W=!0,clearInterval(X),H(Error(A)),c("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),BW($,(K)=>K.sessionId===J.sessionId,A),y$($,(K)=>K.sessionId===J.sessionId,A),$.sessionHost.abort(J.sessionId,A).catch((K)=>{c("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(X),V)clearTimeout(V)}}async function vA($,f){let J=b0(f),Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return v(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((B)=>typeof B==="string"):void 0,X=gw(Q);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let Y;try{Y=await mw($,f,{sessionId:J,prompt:Z,mode:xw(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(B){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(u1(B))return Iw(f,J,B);throw $.publish($.buildEvent("run.failed",{reason:"error",error:B instanceof Error?B.message:String(B)},J)),B}if(Y){let B=await t0($,J),H=kw(Y);if($.publish($.buildEvent(bw(Y.finishReason),{reason:Y.finishReason,...H?{error:H}:{},result:Y,...B?{snapshot:B}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let V=await t0($,J);return l(f,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function cA($,f){let J=b0(f),Q=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";BW($,(Z)=>Z.sessionId===J,Q);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){c("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{y$($,(Z)=>Z.sessionId===J,Q)}return l(f,{applied:!0})}async function uA($,f){let J=p2(f.payload?.payload);if(!J)return v(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),l(f,{applied:!0})}async function dA($,f){switch(f.type){case"chunk":return;case"agent_event":await vw($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([s0($,f.payload.sessionId),t0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},f.payload.sessionId));return}case"ended":await cw($,f);return;default:return}}async function vw($,f){let{sessionId:J,event:Q}=f.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function cw($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),Q=J===f.payload.reason||J==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,W]=await Promise.all([s0($,f.payload.sessionId),t0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await yA(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(Q)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...W?{snapshot:W}:{}},f.payload.sessionId))}import{createSessionId as sA,parseRuntimeConfigExtensions as tA}from"@cline/shared";var iA={};w(iA,{SessionVersioningService:()=>S$,SessionVersioningError:()=>k0});var rA={};w(rA,{trimMessagesToCheckpoint:()=>pA,trimMessagesBeforeCheckpoint:()=>KW,readSessionCheckpointHistory:()=>P6,createRestoredCheckpointMetadata:()=>AW,createCheckpointRestorePlan:()=>GW,applyCheckpointToWorktree:()=>FW});import{execFile as uw}from"node:child_process";import{promisify as dw}from"node:util";var o2=dw(uw);function P6($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let X=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...X?{kind:X}:{}}]})}function AW($,f){let J=P6($).filter((Z)=>Z.runCount<=f),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function lw($,f){return $.reduce((J,Q)=>{if(Q.runCount>f)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function lA($,f){let J=0;for(let Q=0;Q<$.length;Q+=1){let Z=$[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return Q}throw Error(`Could not find user message for checkpoint run ${f}`)}function pA($,f){let J=lA($,f);return $.slice(0,J+1)}function KW($,f){let J=lA($,f);return $.slice(0,J)}function GW($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=lw(P6($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...$.restoreMessages!==!1?{messages:pA($.messages??[],f)}:{}}}async function FW($,f){if((await o2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await o2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await o2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await o2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await o2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await o2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}class k0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function pw($){let f=$.sessionId.trim();if(!f)throw new k0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new k0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new k0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new k0("invalid_restore","checkpointRunCount must be a positive integer");return f}class S${async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,Q=pw({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(Q);if(!Z)throw new k0("session_not_found",`Session ${Q} not found`);let W=f?await $.readMessages(Q):void 0;if(f&&W?.length===0)throw new k0("session_messages_not_found",`No messages found for session ${Q}`);let j=GW({session:Z,messages:W,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??FW)(j.cwd,j.checkpoint);let X=F1({session:Z,messages:W});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let Y=AW(Z,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?KW(W??[],$.checkpointRunCount):j.messages??[],B={sourceSession:Z,sourceMessages:W,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new k0("invalid_restore","start is required when restore.messages is true");let H=$.buildStartInput?await $.buildStartInput(B,$.start):$.start,A=await $.startSession(H),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??aY)(j.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:F1({session:G,messages:V})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as rl,HUB_COMPACTION_CAPABILITY as il,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as nl,HUB_HOOK_CAPABILITY_PREFIX as al,HUB_MISTAKE_LIMIT_CAPABILITY as sl,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as tl,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ol,isHubToolExecutorName as rw}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Qp,HUB_COMPACTION_CAPABILITY as Zp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Wp,HUB_HOOK_CAPABILITY_PREFIX as jp,HUB_MISTAKE_LIMIT_CAPABILITY as Xp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Yp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Vp}from"@cline/shared";var iw=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function yf($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function nw($,f){let J=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",W=yf($.inputSchema);if(!J||!Q||!W||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...yf($.lifecycle)?{lifecycle:yf($.lifecycle)}:{}}}function DW($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let X=nw(Z,J);if(X)f.push(X);continue}if(W==="toolExecutor"){let X=Z.executor;if(!rw(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(W==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(W==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...yf(Z.config)?{config:yf(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...yf(Z.config)?{config:yf(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function aA($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function aw($){return Object.hasOwn($,"update")?$.update:$}function D6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function sw($){let f=($??[]).map(D6).filter(Boolean);return f.length>0?new Set(f):void 0}function tw($,f,J){if(!J)return!0;let Q=D6($),Z=D6(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function PW($,f){let J=sw(f);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>tw(Q.id,Q.name,J))}function nA($,f){let J=async(Q,Z)=>{let W=D6(Q),X=PW($,f).filter((A)=>A.id===W||D6(A.name)===W||A.id.endsWith(`:${W}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Q}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Q}" not found.`;let Y=X[0].skill,V=Z?.trim(),B=V?`
|
|
571
|
+
<command-args>${V}</command-args>`:"",H=Y.description?.trim()?`Description: ${Y.description.trim()}
|
|
563
572
|
|
|
564
|
-
`:"";return`<command-name>${
|
|
573
|
+
`:"";return`<command-name>${Y.name}</command-name>${B}
|
|
565
574
|
<command-instructions>
|
|
566
|
-
${
|
|
567
|
-
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>
|
|
575
|
+
${H}${Y.instructions}
|
|
576
|
+
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>PW($,f).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function ow($,f,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:W,stop:()=>{},refreshType:async()=>{await W()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let Y=j.match(/^\/(\S+)/)?.[1];if(!Y)return j;let V=Z.runtimeCommands.find((B)=>B.name===Y);return V?`${V.instructions}${j.slice(Y.length+1)}`:j},hasConfiguredSkills:(j)=>PW(Z,j).some((X)=>!X.disabled),createSkillsExecutor:(j)=>nA(Z,j),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(j.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>T2(Z.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(j.registerSkillsTool)X.registerTool(m$(nA(Z,j.allowedSkillNames)));for(let Y of Z.runtimeCommands.filter((V)=>V.kind==="skill"&&j.includeSkills||V.kind==="workflow"&&j.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let B=V.trim();return B?`${Y.instructions}
|
|
568
577
|
|
|
569
|
-
${Y}`:X.instructions}})}})}}function gq(f,$,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await Q(f,W.capabilityName,{executor:W.executor,args:X,context:BB(H)},$))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function vq(f,$,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q(f,Z.capabilityName,{toolName:Z.name,input:W,context:BB(j)},$,j.emitUpdate?(X)=>{j.emitUpdate?.(kq(X))}:void 0))?.result}}))}function cq(f,$,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of hq){let H=Z.get(j);if(!H)continue;W[j]=async(X)=>{return(await Q(f,H.capabilityName,{context:X},$))?.control}}return Object.keys(W).length>0?W:void 0}function tW(f){let $=f.contributions.filter((X)=>X.kind==="toolExecutor"),J=f.contributions.filter((X)=>X.kind==="tool"),Q=f.contributions.filter((X)=>X.kind==="hook"),Z=f.contributions.find((X)=>X.kind==="compaction"),W=f.contributions.find((X)=>X.kind==="checkpoint"),j=f.contributions.find((X)=>X.kind==="mistakeLimit"),H=f.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:gq(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...Q.length>0?{hooks:cq(f.sessionId,f.targetClientId,Q,f.requestCapability)}:{},...J.length>0?{extraTools:vq(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...Z?{compaction:{...f.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...W?{checkpoint:{...f.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(X)=>{return(await f.requestCapability(f.sessionId,W.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await f.requestCapability(f.sessionId,j.capabilityName,{context:X},f.targetClientId))?.result}}:{},...H?{userInstructionService:mq(f.sessionId,f.targetClientId,H,f.requestCapability)}:{}}}}var GB="hubCapabilityOwnerClientId";function FB(f,$){f[GB]=$}function uq(f){let $=f?.[GB];return typeof $==="string"&&$.trim()?$.trim():void 0}async function UB(f,$,J){let Q=performance.now(),Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};c("info","session.create.begin",Z);let W=$.payload&&typeof $.payload==="object"?$.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},H=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,X=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let A=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},Y=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!Y)return c("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),v($,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=$.clientId?.trim()||"hub-client",B=aW(X.clientContributions);if(c("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:Y,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)FB(j,V);let P=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||KB(),R=PB(X.configExtensions);c("info","session.create.runtime_build.begin",{...Z,sessionId:P,configExtensionCount:R?.length??0});let G=tW({sessionId:P,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:f.requestCapability});c("info","session.create.start_session.begin",{...Z,sessionId:P,provider:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub")});let F=await f.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...G.localRuntime},capabilities:{toolExecutors:G.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:P,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof A.model==="string"?A.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:H?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():Y),workspaceRoot:H?.workspaceRoot??Y,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!F.result}),s5(f,F.sessionId,V,"creator",{interactive:j.interactive!==!1}),c("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[U,O]=await Promise.all([n0(f,F.sessionId),a0(f,F.sessionId)]);if(c("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!U,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),U)f.publish(f.buildEvent("session.created",{session:U,...O?{snapshot:O}:{}},F.sessionId));return c("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q)}),d($,{session:U,...O?{snapshot:O}:{}})}async function RB(f,$,J){let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():$.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return v($,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},H=j.messages!==!1;if(typeof W!=="number")return v($,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(H&&!X)return v($,"invalid_restore","sessionConfig is required when restore.messages is true");let A=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},Y=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof X?.mode==="string")Y.mode=X.mode;else if(typeof A.mode==="string")Y.mode=A.mode;if(typeof X?.systemPrompt==="string")Y.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")Y.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)Y.checkpointEnabled=!0;let V=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=$.clientId?.trim()||"hub-client",K=aW(A.clientContributions);if(K.length>0)FB(Y,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||KB(),G=PB(A.configExtensions),F=tW({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:f.requestCapability}),O=await new C$().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(y)=>f.sessionHost.getSession(y),readMessages:(y)=>f.sessionHost.readSessionMessages(y),buildStartInput:(y)=>{if(y.restoredCheckpointMetadata)Y.checkpoint=y.restoredCheckpointMetadata;let b=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():y.sourceSession.workspaceRoot||y.sourceSession.cwd;return{source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:{...Y,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:y.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:G,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:y.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:y.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??y.plan.cwd,workspaceRoot:X?.workspaceRoot??b,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 Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(y)=>f.sessionHost.startSession(y),getStartedSessionId:(y)=>y.sessionId,readRestoredSession:(y)=>f.sessionHost.getSession(y)});if(!H)return d($,{checkpoint:O.checkpoint});let M=O.startResult;if(!M)return v($,"restore_failed","Checkpoint restore did not start a session");s5(f,M.sessionId,B,"creator",{interactive:Y.interactive!==!1});let[L,D]=await Promise.all([n0(f,M.sessionId),a0(f,M.sessionId)]);if(L)f.publish(f.buildEvent("session.created",{session:L,...D?{snapshot:D}:{}},M.sessionId));return d($,{session:L,...D?{snapshot:D}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(X){if(X instanceof h0)return v($,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return v($,"restore_failed",X instanceof Error?X.message:String(X))}}async function DB(f,$){let J=E0($);if(!J)return v($,"invalid_session_attach","session.attach requires a session id");s5(f,J,$.clientId?.trim()||"hub-client","participant");let Q=await n0(f,J);if(Q)f.publish(f.buildEvent("session.attached",{session:Q},J));return Q?d($,{session:Q}):v($,"session_not_found",`Unknown session: ${J}`)}async function LB(f,$){let J=E0($);if(!J)return v($,"invalid_session_detach","session.detach requires a session id");let Q=$.clientId?.trim()||"hub-client",[Z]=await Promise.all([n0(f,J)]),W=uq(Z?.metadata)??Q,j=f.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)f.sessionState.delete(J)}w$(f,(A)=>A.sessionId===J&&A.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[H,X]=await Promise.all([n0(f,J),a0(f,J)]);return f.publish(f.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},J)),d($)}async function _B(f,$){let J=E0($),Q=$.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([n0(f,J),Q?a0(f,J):Promise.resolve(void 0)]);return Z?d($,{session:Z,...W?{snapshot:W}:{}}):v($,"session_not_found",`Unknown session: ${J}`)}async function OB(f,$){let J=E0($);if(!J)return v($,"invalid_session_id","session.messages requires a session id");if(!await n0(f,J))return v($,"session_not_found",`Unknown session: ${J}`);let Z=await f.sessionHost.readSessionMessages(J);return d($,{sessionId:J,messages:Z})}async function TB(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,Z=(await f.sessionHost.listSessions(J)).map((W)=>a5(W,f.sessionState.get(W.sessionId)));return d($,{sessions:Z})}async function zB(f,$){let J=E0($),Q=t5($.payload?.metadata),Z=await f.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([n0(f,J),a0(f,J)]);if(W)f.publish(f.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:$.version,requestId:$.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function MB(f,$){let J=E0($),Q=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),d($,{deleted:Q})}async function NB(f,$){let J=E0($),Q=f.sessionHost.pendingPrompts;if(!Q)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return d($,{sessionId:J,prompts:Z})}async function qB(f,$){let J=E0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,W=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,j=f.sessionHost.pendingPrompts;if(!j)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return d($,H)}async function yB(f,$){let J=E0($),Q=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",Z=f.sessionHost.pendingPrompts;if(!Z)return v($,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return d($,W)}function wB(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 lq=new Set(["skills","workflows","rules","tools","mcp"]);function sW(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function Y4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function pq(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function CB(f){if(f===void 0)return{};if(!sW(f))throw Error("settings.list payload must be an object.");return{cwd:Y4(f,"cwd"),workspaceRoot:Y4(f,"workspaceRoot"),availabilityContext:sW(f.availabilityContext)?f.availabilityContext:void 0}}function rq(f){if(!sW(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!lq.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...CB(f),type:$,id:Y4(f,"id"),path:Y4(f,"path"),name:Y4(f,"name"),enabled:pq(f,"enabled")}}class l2{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=dq("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new Df({sessionService:new Rf(new Ff),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:f.telemetry,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:M1,requestCapability:($,J,Q,Z,W)=>aV(this.ctx,$,J,Q,Z,W)},this.schedules=new g2({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let Q=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(M1(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new m2(this.schedules),this.settings=f.settingsService??new L$,f.cronOptions)this.cronService=new mJ({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{jB(this.ctx,$).catch((J)=>{dW("session event handling failed",J),o5(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:$.type,sessionId:$.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())cW(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(w$(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){try{let $=await this.dispatchCommand(f);return this.captureFailedReply(f,$),$}catch($){throw o5(this.options.telemetry,{component:"core",operation:"hub.command",error:$,severity:"error",handled:!1,context:this.commandTelemetryContext(f)}),$}}async dispatchCommand(f){switch(f.command){case"client.register":return eV(this.ctx,f);case"client.update":return fB(this.ctx,f);case"client.unregister":return $B(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return JB(this.ctx,f);case"session.create":return await UB(this.ctx,f,($)=>vW(this.ctx,$));case"session.restore":return await RB(this.ctx,f,($)=>vW(this.ctx,$));case"session.attach":return await DB(this.ctx,f);case"session.detach":return await LB(this.ctx,f);case"session.get":return await _B(this.ctx,f);case"session.messages":return await OB(this.ctx,f);case"session.list":return await TB(this.ctx,f);case"session.update":return await zB(this.ctx,f);case"session.pending_prompts":return await NB(this.ctx,f);case"session.update_pending_prompt":return await qB(this.ctx,f);case"session.remove_pending_prompt":return await yB(this.ctx,f);case"session.delete":return await MB(this.ctx,f);case"session.hook":return await WB(this.ctx,f);case"run.start":case"session.send_input":return await QB(this.ctx,f);case"run.abort":return await ZB(this.ctx,f);case"capability.request":return await sV(this.ctx,f);case"approval.respond":return await iV(this.ctx,f);case"capability.respond":return oV(this.ctx,f);case"capability.progress":return tV(this.ctx,f);case"ui.notify":return this.publish(M1("ui.notify",f.payload??{})),d(f);case"ui.show_window":return this.publish(M1("ui.show_window",f.payload??{})),d(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=wB(f.command);if(J)this.publish(M1(J,$.payload))}return $}}}captureFailedReply(f,$){if($.ok||!$.error||!iq($.error.code))return;o5(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error($.error.message),severity:$.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext(f),errorCode:$.error.code}})}commandTelemetryContext(f){return{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:typeof f.payload?.sessionId==="string"?f.payload.sessionId:f.sessionId}}async handleSettingsList(f){try{let $=await this.settings.list(CB(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(rq(f.payload));return this.publish(M1("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 Q=this.listeners.get(f)??new Set,Z={sessionId:J?.sessionId,listener:$};return Q.add(Z),this.listeners.set(f,Q),()=>{let W=this.listeners.get(f);if(!W)return;if(W.delete(Z),W.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($);w$(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(Q){dW(`listener threw while publishing ${f.event}`,Q),o5(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:f.event,sessionId:f.sessionId}})}}}}function iq(f){return f==="session_not_found"||f==="session_messages_not_found"||f==="hub_command_timeout"||f.endsWith("_failed")}import{timingSafeEqual as sq}from"node:crypto";import oq from"node:http";import eq from"node:net";import{URL as hB}from"node:url";import{WebSocketServer as fy}from"ws";import{captureSdkError as SB,HUB_COMMAND_SLOW_LOG_MS as nq,resolveHubCommandTimeoutMs as aq,safeJsonParse as tq}from"@cline/shared";function oW(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function EB(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class V4{transport;telemetry;constructor(f,$){this.transport=f;this.telemetry=$}attach(f){let $=new Map,J=new Set,Q=!1,Z=(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)}`)}},W=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let Y=performance.now(),V=!1,B=oW(A);c("info","command.start",B);let K=setTimeout(()=>{if(V)return;c("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-Y)})},nq),P=this.transport.command(A.envelope);P.then((M)=>{if(!V)return;c(M.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-Y),ok:M.ok,errorCode:M.error?.code,errorMessage:M.error?.message})},(M)=>{if(!V)return;c("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-Y),error:M})});let R=!1,G,F,U=aq(A.envelope.command,A.envelope.timeoutMs);try{F=U===null?await P:await Promise.race([P,new Promise((M)=>{G=setTimeout(()=>{R=!0,SB(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${A.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),M(EB(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},U)})])}catch(M){if(clearTimeout(K),G)clearTimeout(G);throw M}if(V=R,clearTimeout(K),G)clearTimeout(G);let O=Math.round(performance.now()-Y);if(R)c("error","command.timeout",{...B,durationMs:O,timeoutMs:U});else c(F.ok?"info":"warn","command.end",{...B,durationMs:O,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let L=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(L)J.add(L)}else if(A.envelope.command==="client.unregister"&&F.ok){let M=A.envelope.clientId?.trim();if(M)J.delete(M)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;if($.has(Y))break;let V=await this.transport.subscribe(A.clientId,W,{sessionId:A.sessionId});$.set(Y,V);break}case"stream.unsubscribe":{let Y=`${A.clientId}:${A.sessionId??"*"}`;$.get(Y)?.(),$.delete(Y);break}case"reply":case"event":break}}catch(A){let Y=typeof X.data==="string"?tq(X.data):void 0;if(!Y||Y.kind!=="command"){c("error","rejected malformed websocket frame",{error:A});return}c("error","command.error",{...oW(Y),error:A}),SB(this.telemetry,{component:"core",operation:"hub.websocket_command",error:A,severity:"error",handled:!0,context:oW(Y)}),Z({kind:"reply",envelope:EB(Y,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},H=()=>{if(Q)return;Q=!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",j),f.removeEventListener("close",H)};return f.addEventListener("message",j),f.addEventListener("close",H),H}}class B4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function $y(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 Jy(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(Q)=>{J({data:$y(Q)})});return}f.on("close",J)},removeEventListener(){}}}function Qy(f){try{f.write(`HTTP/1.1 400 Bad Request\r
|
|
578
|
+
${B}`:Y.instructions}})}})}}function ew($,f,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let X=j.at(-1),Y=j.slice(0,-1);return(await Q($,W.capabilityName,{executor:W.executor,args:Y,context:aA(X)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function $y($,f,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q($,Z.capabilityName,{toolName:Z.name,input:W,context:aA(j)},f,j.emitUpdate?(Y)=>{j.emitUpdate?.(aw(Y))}:void 0))?.result}}))}function fy($,f,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of iw){let X=Z.get(j);if(!X)continue;W[j]=async(Y)=>{return(await Q($,X.capabilityName,{context:Y},f))?.control}}return Object.keys(W).length>0?W:void 0}function RW($){let f=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),J=$.contributions.filter((Y)=>Y.kind==="tool"),Q=$.contributions.filter((Y)=>Y.kind==="hook"),Z=$.contributions.find((Y)=>Y.kind==="compaction"),W=$.contributions.find((Y)=>Y.kind==="checkpoint"),j=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:ew($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...Q.length>0?{hooks:fy($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J.length>0?{extraTools:$y($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...W?{checkpoint:{...$.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:ow($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var oA="hubCapabilityOwnerClientId";function eA($,f){$[oA]=f}function Jy($){let f=$?.[oA];return typeof f==="string"&&f.trim()?f.trim():void 0}async function $K($,f,J){let Q=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};c("info","session.create.begin",Z);let W=f.payload&&typeof f.payload==="object"?f.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,Y=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof X?.mode==="string")j.mode=X.mode;else if(typeof Y.mode==="string")j.mode=Y.mode;if(typeof X?.systemPrompt==="string")j.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")j.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)j.checkpointEnabled=!0;let V=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!B)return c("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),v(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let H=f.clientId?.trim()||"hub-client",A=DW(Y.clientContributions);if(c("info","session.create.contributions_parsed",{...Z,clientId:H,workspaceRoot:B,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:A.length}),A.length>0)eA(j,H);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||sA(),R=tA(Y.configExtensions);c("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let P=RW({sessionId:G,targetClientId:H,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});c("info","session.create.start_session.begin",{...Z,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof j.provider==="string"?j.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof j.model==="string"?j.model:"hub")});let F=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof j.model==="string"?j.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():B),workspaceRoot:X?.workspaceRoot??B,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!F.result}),B9($,F.sessionId,H,"creator",{interactive:j.interactive!==!1}),c("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[D,_]=await Promise.all([s0($,F.sessionId),t0($,F.sessionId)]);if(c("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!D,hasSnapshot:!!_,elapsedMs:Math.round(performance.now()-Q)}),D)$.publish($.buildEvent("session.created",{session:D,..._?{snapshot:_}:{}},F.sessionId));return c("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-Q)}),l(f,{session:D,..._?{snapshot:_}:{}})}async function fK($,f,J){let Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():f.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return v(f,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},X=j.messages!==!1;if(typeof W!=="number")return v(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(X&&!Y)return v(f,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},B=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof Y?.mode==="string")B.mode=Y.mode;else if(typeof V.mode==="string")B.mode=V.mode;if(typeof Y?.systemPrompt==="string")B.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")B.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)B.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)B.checkpointEnabled=!0;let H=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},A=f.clientId?.trim()||"hub-client",K=DW(V.clientContributions);if(K.length>0)eA(B,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||sA(),P=tA(V.configExtensions),F=RW({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),_=await new S$().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)B.checkpoint=N.restoredCheckpointMetadata;let y=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof B.source==="string"?B.source:void 0,interactive:B.interactive!==!1,sessionMetadata:{...B,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:N.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:P,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:N.sourceSession.provider),modelId:Y?.modelId??(typeof H.model==="string"?H.model:N.sourceSession.model),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:""),cwd:Y?.cwd??N.plan.cwd,workspaceRoot:Y?.workspaceRoot??y,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof B.teamName==="string"?B.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!X)return l(f,{checkpoint:_.checkpoint});let O=_.startResult;if(!O)return v(f,"restore_failed","Checkpoint restore did not start a session");B9($,O.sessionId,A,"creator",{interactive:B.interactive!==!1});let[z,U]=await Promise.all([s0($,O.sessionId),t0($,O.sessionId)]);if(z)$.publish($.buildEvent("session.created",{session:z,...U?{snapshot:U}:{}},O.sessionId));return l(f,{session:z,...U?{snapshot:U}:{},messages:_.messages??[],checkpoint:_.checkpoint})}catch(Y){if(Y instanceof k0)return v(f,Y.code,Y.code==="session_not_found"?`Unknown session: ${Z}`:Y.message);return v(f,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function JK($,f){let J=b0(f);if(!J)return v(f,"invalid_session_attach","session.attach requires a session id");B9($,J,f.clientId?.trim()||"hub-client","participant");let Q=await s0($,J);if(Q)$.publish($.buildEvent("session.attached",{session:Q},J));return Q?l(f,{session:Q}):v(f,"session_not_found",`Unknown session: ${J}`)}async function QK($,f){let J=b0(f);if(!J)return v(f,"invalid_session_detach","session.detach requires a session id");let Q=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([s0($,J)]),W=Jy(Z?.metadata)??Q,j=$.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)$.sessionState.delete(J)}y$($,(V)=>V.sessionId===J&&V.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[X,Y]=await Promise.all([s0($,J),t0($,J)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Q}:{clientId:Q},J)),l(f)}async function ZK($,f){let J=b0(f),Q=f.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([s0($,J),Q?t0($,J):Promise.resolve(void 0)]);return Z?l(f,{session:Z,...W?{snapshot:W}:{}}):v(f,"session_not_found",`Unknown session: ${J}`)}async function WK($,f){let J=b0(f);if(!J)return v(f,"invalid_session_id","session.messages requires a session id");if(!await s0($,J))return v(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return l(f,{sessionId:J,messages:Z})}async function jK($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((W)=>Y9(W,$.sessionState.get(W.sessionId)));return l(f,{sessions:Z})}async function XK($,f){let J=b0(f),Q=V9(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([s0($,J),t0($,J)]);if(W)$.publish($.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function YK($,f){let J=b0(f),Q=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),l(f,{deleted:Q})}async function VK($,f){let J=b0(f),Q=$.sessionHost.pendingPrompts;if(!Q)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return l(f,{sessionId:J,prompts:Z})}async function BK($,f){let J=b0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,W=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return l(f,X)}async function HK($,f){let J=b0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return v(f,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return l(f,W)}function AK($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var Zy=new Set(["skills","workflows","rules","tools","mcp"]);function UW($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R6($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function Wy($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function KK($){if($===void 0)return{};if(!UW($))throw Error("settings.list payload must be an object.");return{cwd:R6($,"cwd"),workspaceRoot:R6($,"workspaceRoot"),availabilityContext:UW($.availabilityContext)?$.availabilityContext:void 0}}function jy($){if(!UW($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!Zy.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...KK($),type:f,id:R6($,"id"),path:R6($,"path"),name:R6($,"name"),enabled:Wy($,"enabled")}}class e2{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=Qy("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new z1({sessionService:new U1(new D1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(f)=>this.publish(f),buildEvent:wf,requestCapability:(f,J,Q,Z,W)=>EA(this.ctx,f,J,Q,Z,W)},this.schedules=new n2({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let Q=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(wf(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new i2(this.schedules),this.settings=$.settingsService??new L$,$.cronOptions)this.cronService=new n4({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{dA(this.ctx,f).catch((J)=>{HW("session event handling failed",J),H9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())VW(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(y$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw H9(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return IA(this.ctx,$);case"client.update":return xA(this.ctx,$);case"client.unregister":return gA(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return mA(this.ctx,$);case"session.create":return await $K(this.ctx,$,(f)=>YW(this.ctx,f));case"session.restore":return await fK(this.ctx,$,(f)=>YW(this.ctx,f));case"session.attach":return await JK(this.ctx,$);case"session.detach":return await QK(this.ctx,$);case"session.get":return await ZK(this.ctx,$);case"session.messages":return await WK(this.ctx,$);case"session.list":return await jK(this.ctx,$);case"session.update":return await XK(this.ctx,$);case"session.pending_prompts":return await VK(this.ctx,$);case"session.update_pending_prompt":return await BK(this.ctx,$);case"session.remove_pending_prompt":return await HK(this.ctx,$);case"session.delete":return await YK(this.ctx,$);case"session.hook":return await uA(this.ctx,$);case"run.start":case"session.send_input":return await vA(this.ctx,$);case"run.abort":return await cA(this.ctx,$);case"capability.request":return await bA(this.ctx,$);case"approval.respond":return await SA(this.ctx,$);case"capability.respond":return kA(this.ctx,$);case"capability.progress":return hA(this.ctx,$);case"ui.notify":return this.publish(wf("ui.notify",$.payload??{})),l($);case"ui.show_window":return this.publish(wf("ui.show_window",$.payload??{})),l($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=AK($.command);if(J)this.publish(wf(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!Xy(f.error.code))return;H9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(KK($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(jy($.payload));return this.publish(wf("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let Q=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return Q.add(Z),this.listeners.set($,Q),()=>{let W=this.listeners.get($);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);y$(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(Q){HW(`listener threw while publishing ${$.event}`,Q),H9(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Xy($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as Hy}from"node:crypto";import Ay from"node:http";import Ky from"node:net";import{URL as PK}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as DK,HUB_CAPABILITIES as Gy,isHubProtocolCompatible as Fy,MAX_CLIENT_HUB_PROTOCOL_VERSION as RK,MIN_CLIENT_HUB_PROTOCOL_VERSION as UK}from"@cline/shared";import{WebSocketServer as Py}from"ws";import{captureSdkError as GK,HUB_COMMAND_SLOW_LOG_MS as Yy,resolveHubCommandTimeoutMs as Vy,safeJsonParse as By}from"@cline/shared";function zW($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function FK($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class U6{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,Q=!1,Z=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},W=(Y)=>{Z({kind:"event",envelope:Y})},j=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let B=performance.now(),H=!1,A=zW(V);c("info","command.start",A);let K=setTimeout(()=>{if(H)return;c("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-B)})},Yy),G=this.transport.command(V.envelope);G.then((O)=>{if(!H)return;c(O.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-B),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!H)return;c("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-B),error:O})});let R=!1,P,F,D=Vy(V.envelope.command,V.envelope.timeoutMs);try{F=D===null?await G:await Promise.race([G,new Promise((O)=>{P=setTimeout(()=>{R=!0,GK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${D}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:D}}),O(FK(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${D}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},D)})])}catch(O){if(clearTimeout(K),P)clearTimeout(P);throw O}if(H=R,clearTimeout(K),P)clearTimeout(P);let _=Math.round(performance.now()-B);if(R)c("error","command.timeout",{...A,durationMs:_,timeoutMs:D});else c(F.ok?"info":"warn","command.end",{...A,durationMs:_,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(V.envelope.command==="client.register"&&F.ok){let z=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(z)J.add(z)}else if(V.envelope.command==="client.unregister"&&F.ok){let O=V.envelope.clientId?.trim();if(O)J.delete(O)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let B=`${V.clientId}:${V.sessionId??"*"}`;if(f.has(B))break;let H=await this.transport.subscribe(V.clientId,W,{sessionId:V.sessionId});f.set(B,H);break}case"stream.unsubscribe":{let B=`${V.clientId}:${V.sessionId??"*"}`;f.get(B)?.(),f.delete(B);break}case"reply":case"event":break}}catch(V){let B=typeof Y.data==="string"?By(Y.data):void 0;if(!B||B.kind!=="command"){c("error","rejected malformed websocket frame",{error:V});return}c("error","command.error",{...zW(B),error:V}),GK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:zW(B)}),Z({kind:"reply",envelope:FK(B,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Q)return;Q=!0;for(let Y of f.values())Y();f.clear();for(let Y of J)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",X)};return $.addEventListener("message",j),$.addEventListener("close",X),X}}class z6{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function Dy($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function Ry($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(Q)=>{J({data:Dy(Q)})});return}$.on("close",J)},removeEventListener(){}}}function Uy($){try{$.write(`HTTP/1.1 400 Bad Request\r
|
|
570
579
|
Connection: close\r
|
|
571
580
|
Content-Length: 0\r
|
|
572
581
|
\r
|
|
573
|
-
`)
|
|
582
|
+
`),$.end()}catch{$.destroy()}}function zy($){try{$.write(`HTTP/1.1 401 Unauthorized\r
|
|
574
583
|
Connection: close\r
|
|
575
584
|
Content-Length: 0\r
|
|
576
585
|
\r
|
|
577
|
-
`)
|
|
578
|
-
Caused by: ${
|
|
579
|
-
`).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0
|
|
580
|
-
`,"utf8")}persistRuntime(f
|
|
581
|
-
`,"utf8"),
|
|
586
|
+
`),$.end()}catch{$.destroy()}}function LW($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),Q=Buffer.from(f,"utf8");return J.length===Q.length&&Hy(J,Q)}function zK($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,W.code=J;if($ instanceof Error&&$.stack)W.stack=`${W.name}: ${W.message}
|
|
587
|
+
Caused by: ${$.stack}`;return W}async function Ly($){return await new Promise((f,J)=>{let Q=Ky.createServer();Q.once("error",J),Q.listen(0,$,()=>{let Z=Q.address();if(!Z||typeof Z==="string"){Q.close(()=>J(Error("Failed to resolve free port")));return}let W=Z.port;Q.close((j)=>{if(j){J(j);return}f(W)})})})}function _y($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var _W=new Map,LK="cline-hub-auth.",Oy=30000;function OK($){return Array.isArray($)?$.join(","):$??""}function _K($){return $===32||$===9}function A9($){let f=OK($).trim(),J="bearer";if(f.length<=6||f.slice(0,6).toLowerCase()!=="bearer"||!_K(f.charCodeAt(6)))return null;let Q=7;while(Q<f.length&&_K(f.charCodeAt(Q)))Q+=1;return f.slice(Q).trim()||null}function My($){for(let f of OK($).split(",")){let J=f.trim();if(J.startsWith(LK))return J.slice(LK.length).trim()||null}return null}async function Sf($){let f=$.owner??d1(),J=$.host??"127.0.0.1",Q=$.pathname??"/hub",Z=$.port??C2(),W=Z===0?await Ly(J):Z,j=W,X=Z1(J,W,Q),Y=m5(),V=g5(),B=new e2($);await B.start();let H=new U6(new z6(B),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:DK,minClientProtocolVersion:UK,maxClientProtocolVersion:RK,capabilities:Gy,coreVersion:t4.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,P,F,D=async()=>{if(F)return F;return F=(async()=>{if(P)clearInterval(P),P=void 0;for(let U of R)U.terminate?.();R.clear();for(let U of A)U();if(A.clear(),await new Promise((U,N)=>{O.close((y)=>{if(y){N(y);return}U()})}),await new Promise((U,N)=>{_.close((y)=>{if(y){N(y);return}U()})}),await B.stop(),(await H0(f.discoveryPath))?.url===X)await C0(f.discoveryPath)})(),F},_=Ay.createServer((z,U)=>{if((z.url??"/")==="/health"){let y=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:J,port:j,url:X});U.statusCode=200,U.setHeader("content-type","application/json"),U.end(y);return}if((z.url??"/")==="/status"){if(!LW(A9(z.headers.authorization),V)){U.statusCode=401,U.end("Unauthorized");return}let y=JSON.stringify({hubId:B.getHubId(),...G,authToken:V,host:J,port:j,url:X,updatedAt:new Date().toISOString()});U.statusCode=200,U.setHeader("content-type","application/json"),U.end(y);return}if((z.url??"/")==="/version"){U.statusCode=200,U.setHeader("content-type","application/json"),U.end(JSON.stringify(G));return}if(new PK(z.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&z.method==="POST"){if(!LW(A9(z.headers.authorization),V)){U.statusCode=401,U.end("Unauthorized");return}U.statusCode=202,U.setHeader("content-type","application/json"),U.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{D()});return}U.statusCode=404,U.end("Not found")}),O=new Py({noServer:!0});P=setInterval(()=>{for(let z of R){if(z.isAlive===!1){try{z.terminate?.()}catch{}R.delete(z);continue}z.isAlive=!1;try{z.ping?.()}catch{try{z.terminate?.()}catch{}R.delete(z)}}},Oy),_.on("upgrade",(z,U,N)=>{if(new PK(z.url??"/",`http://${J}:${j}`).pathname!==Q){U.destroy();return}if(!LW(My(z.headers["sec-websocket-protocol"]),V)){zy(U);return}try{O.handleUpgrade(z,U,N,(h)=>{let u=h;u.isAlive=!0,u.on("pong",()=>{u.isAlive=!0}),R.add(u);let t=H.attach(Ry(h));A.add(t),h.once("close",()=>{R.delete(u),t(),A.delete(t)})})}catch{Uy(U)}});try{await new Promise((z,U)=>{_.once("error",(N)=>{U(zK(N,{host:J,port:W,pathname:Q}))}),_.listen(W,J,()=>{let N=_.address();if(!N||typeof N==="string"){U(zK(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=N.port,X=Z1(J,j,Q),z()})})}catch(z){if(P)clearInterval(P),P=void 0;throw await B.stop().catch(()=>{return}),z}return await v5(f.discoveryPath,{hubId:B.getHubId(),protocolVersion:DK,minClientProtocolVersion:UK,maxClientProtocolVersion:RK,capabilities:[...G.capabilities],coreVersion:t4.version,buildId:Y,authToken:V,host:J,port:j,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:X,authToken:V,close:D}}async function K9($){let f=$.owner??d1(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",Z=$.port??C2(),W=$.pathname??"/hub",j=Z1(Q,Z,W),X=f.discoveryPath,Y=(B)=>{if(!J)T$(B.url,B.authToken);return B},V=_W.get(X);if(V){let B=await V;if(B.url===j)return Y({server:B,url:B.url,authToken:B.authToken,action:"reuse"})}return await c5(f.discoveryPath,async()=>{let B=await H0(f.discoveryPath);if(B?.url&&(B.url===j||$.allowPortFallback===!0)){let K=await l1(B.url,{authToken:B.authToken});if(K?.url&&Fy(K).compatible&&await G1(K.url,{authToken:B.authToken}))return Y({url:K.url,authToken:B.authToken,action:"reuse"})}if(B?.url)await C0(f.discoveryPath);let A=async(K)=>{let G=Sf({...K,owner:f});_W.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw _W.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!_y(K))throw K;return await A({...$,port:0})}})}function TK(){return MK()==="production"?n0():E0()}function Ty($){return MK()!=="production"&&!$}async function NK($){let f=i0({host:$.host,port:$.port,pathname:$.pathname});return await Sf({...$,...f,owner:TK()})}async function qK($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=i0({host:$.host,port:$.port,pathname:$.pathname});return await K9({...$,...J,allowPortFallback:$.allowPortFallback??Ty(f),owner:TK()})}F9();var SK={};w(SK,{registerRemoteConfigSessionBlobUpload:()=>R9,readRemoteConfigSessionBlobUploadMetadata:()=>OW,prepareRemoteConfigCoreIntegration:()=>TW,createRemoteConfigSessionMessagesArtifactUploader:()=>MW,buildRemoteConfigSessionBlobUploadMetadata:()=>P9,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>D9});import{buildRemoteConfigSessionBlobUploadMetadata as P9,clearRemoteConfigSessionBlobUpload as Ny,createClineTelemetryServiceConfig as qy,createSessionId as wy,createRemoteConfigSessionMessagesArtifactUploader as yy,prepareRemoteConfigRuntime as Sy,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as D9,readRemoteConfigSessionBlobUploadMetadata as OW,registerRemoteConfigSessionBlobUpload as R9}from"@cline/shared";function Cy($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return a1(qy(J)).telemetry}function MW(){let $=yy();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function TW($){let f=await Sy($),J=Cy(f,$),Q=[f.pluginDefinition],Z=f.claims?.subject,W=P9(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:Q,telemetry:J,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,B=W?X.config.sessionId?.trim()||wy():X.config.sessionId;if(B&&W)j=B;let H=B&&W?R9(B,f.bundle?.remoteConfig,Z):void 0,A=H?{...X.sessionMetadata??{},[D9]:H}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...B?{sessionId:B}:{},extensions:[...Y,...Q],telemetry:J??V}}},async dispose(){if(j)Ny(j)}}}var xK={};w(xK,{createTeamName:()=>L9,DefaultRuntimeBuilder:()=>J8});import{hasRuntimeConfigExtension as py}from"@cline/shared";import{nanoid as ry}from"nanoid";H1();var IK={};w(IK,{createLocalTeamStore:()=>yW,SqliteTeamStore:()=>Cf,FileTeamStore:()=>L6});import{appendFileSync as Ey,existsSync as $8,mkdirSync as CK,readdirSync as hy,readFileSync as EK,renameSync as by,writeFileSync as ky}from"node:fs";import{join as NW}from"node:path";import{resolveTeamDataDir as Iy}from"@cline/shared/storage";function hK(){return new Date().toISOString()}function qW($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function bK($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class L6{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Iy()}init(){this.ensureTeamDir()}listTeamNames(){if(!$8(this.teamDirPath))return[];return hy(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>$8(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?bK(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!$8(J))return[];return EK(J,"utf8").split(`
|
|
588
|
+
`).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?bK(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),Ey(this.historyPath($),`${JSON.stringify({ts:hK(),eventType:f.type,payload:f})}
|
|
589
|
+
`,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let Q={version:1,updatedAt:hK(),teamState:f,teammates:J},Z=this.statePath($),W=`${Z}.tmp`;ky(W,`${JSON.stringify(Q,null,2)}
|
|
590
|
+
`,"utf8"),by(W,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let Q=J.teamState.runs.filter((W)=>W.status==="queued"||W.status==="running").map((W)=>W.id);if(Q.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((W)=>W.status==="queued"||W.status==="running"?{...W,status:"interrupted",error:f,endedAt:Z}:W)},this.persistRuntime($,J.teamState,J.teammates),Q}ensureTeamDir(){if(!$8(this.teamDirPath))CK(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=NW(this.ensureTeamDir(),qW($));if(!$8(f))CK(f,{recursive:!0});return f}statePath($){return NW(this.ensureTeamDir(),qW($),"state.json")}historyPath($){return NW(this.ensureTeamDir(),qW($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!$8(f))return;try{let J=JSON.parse(EK(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as xy,mkdirSync as gy}from"node:fs";import{join as my}from"node:path";import{safeJsonParse as kK}from"@cline/shared";import{loadSqliteDb as vy,nowIso as wW}from"@cline/shared/db";import{resolveDbDataDir as cy}from"@cline/shared/storage";function uy(){return cy()}function f8($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function dy($){let f=kK($);if(!Array.isArray(f))return[];let J=[];for(let Q of f){if(!Q||typeof Q!=="object")continue;let Z=Q,W=Z.agentId,j=Z.rolePrompt;if(typeof W!=="string"||!W.trim())continue;if(typeof j!=="string"||!j.trim())continue;let X={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())X.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))X.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(X)}return J}function ly($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class Cf{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??uy()}init(){this.getRawDb()}ensureTeamDir(){if(!xy(this.teamDirPath))gy(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return my(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=vy(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
|
|
582
591
|
CREATE TABLE IF NOT EXISTS team_store_schema_version (
|
|
583
592
|
lock INTEGER PRIMARY KEY CHECK (lock = 1),
|
|
584
593
|
version INTEGER NOT NULL
|
|
585
594
|
);
|
|
586
|
-
`)
|
|
595
|
+
`),!$.prepare("SELECT version FROM team_store_schema_version WHERE lock = 1").get())$.prepare("INSERT INTO team_store_schema_version (lock, version) VALUES (1, 1)").run();$.exec(`
|
|
587
596
|
CREATE TABLE IF NOT EXISTS team_events (
|
|
588
597
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
589
598
|
team_name TEXT NOT NULL,
|
|
@@ -593,17 +602,17 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
593
602
|
causation_id TEXT,
|
|
594
603
|
correlation_id TEXT
|
|
595
604
|
);
|
|
596
|
-
`)
|
|
605
|
+
`),$.exec(`
|
|
597
606
|
CREATE INDEX IF NOT EXISTS idx_team_events_name_ts
|
|
598
607
|
ON team_events(team_name, ts DESC);
|
|
599
|
-
`)
|
|
608
|
+
`),$.exec(`
|
|
600
609
|
CREATE TABLE IF NOT EXISTS team_runtime_snapshot (
|
|
601
610
|
team_name TEXT PRIMARY KEY,
|
|
602
611
|
state_json TEXT NOT NULL,
|
|
603
612
|
teammates_json TEXT NOT NULL,
|
|
604
613
|
updated_at TEXT NOT NULL
|
|
605
614
|
);
|
|
606
|
-
`)
|
|
615
|
+
`),$.exec(`
|
|
607
616
|
CREATE TABLE IF NOT EXISTS team_tasks (
|
|
608
617
|
team_name TEXT NOT NULL,
|
|
609
618
|
task_id TEXT NOT NULL,
|
|
@@ -617,7 +626,7 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
617
626
|
updated_at TEXT NOT NULL,
|
|
618
627
|
PRIMARY KEY(team_name, task_id)
|
|
619
628
|
);
|
|
620
|
-
`)
|
|
629
|
+
`),$.exec(`
|
|
621
630
|
CREATE TABLE IF NOT EXISTS team_runs (
|
|
622
631
|
team_name TEXT NOT NULL,
|
|
623
632
|
run_id TEXT NOT NULL,
|
|
@@ -633,10 +642,10 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
633
642
|
version INTEGER NOT NULL DEFAULT 1,
|
|
634
643
|
PRIMARY KEY(team_name, run_id)
|
|
635
644
|
);
|
|
636
|
-
`)
|
|
645
|
+
`),$.exec(`
|
|
637
646
|
CREATE INDEX IF NOT EXISTS idx_team_runs_status
|
|
638
647
|
ON team_runs(team_name, status);
|
|
639
|
-
`)
|
|
648
|
+
`),$.exec(`
|
|
640
649
|
CREATE TABLE IF NOT EXISTS team_outcomes (
|
|
641
650
|
team_name TEXT NOT NULL,
|
|
642
651
|
outcome_id TEXT NOT NULL,
|
|
@@ -647,7 +656,7 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
647
656
|
version INTEGER NOT NULL DEFAULT 1,
|
|
648
657
|
PRIMARY KEY(team_name, outcome_id)
|
|
649
658
|
);
|
|
650
|
-
`)
|
|
659
|
+
`),$.exec(`
|
|
651
660
|
CREATE TABLE IF NOT EXISTS team_outcome_fragments (
|
|
652
661
|
team_name TEXT NOT NULL,
|
|
653
662
|
outcome_id TEXT NOT NULL,
|
|
@@ -662,13 +671,13 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
662
671
|
version INTEGER NOT NULL DEFAULT 1,
|
|
663
672
|
PRIMARY KEY(team_name, fragment_id)
|
|
664
673
|
);
|
|
665
|
-
`)}run(f
|
|
666
|
-
VALUES (?, ?, ?, ?, NULL, ?)`,[
|
|
674
|
+
`)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f8($)]);if(!f)return;let J=kK(f.state_json);if(!J)return;try{return ly(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 ?",[f8($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=f8($),J=this.readState(f),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=Q?dy(Q.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
|
|
675
|
+
VALUES (?, ?, ?, ?, NULL, ?)`,[f8($),wW(),f,JSON.stringify(J),Q??null])}persistRuntime($,f,J){let Q=f8($),Z=wW();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
667
676
|
VALUES (?, ?, ?, ?)
|
|
668
677
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
669
678
|
state_json = excluded.state_json,
|
|
670
679
|
teammates_json = excluded.teammates_json,
|
|
671
|
-
updated_at = excluded.updated_at`,[Q,JSON.stringify(
|
|
680
|
+
updated_at = excluded.updated_at`,[Q,JSON.stringify(f),JSON.stringify(J),Z]);for(let W of f.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
|
|
672
681
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
|
|
673
682
|
ON CONFLICT(team_name, task_id) DO UPDATE SET
|
|
674
683
|
title = excluded.title,
|
|
@@ -678,7 +687,7 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
678
687
|
depends_on_json = excluded.depends_on_json,
|
|
679
688
|
summary = excluded.summary,
|
|
680
689
|
version = team_tasks.version + 1,
|
|
681
|
-
updated_at = excluded.updated_at`,[Q,W.id,W.title,W.description,W.status,W.assignee??null,JSON.stringify(W.dependsOn??[]),W.summary??null,W.updatedAt.toISOString()]);for(let W of
|
|
690
|
+
updated_at = excluded.updated_at`,[Q,W.id,W.title,W.description,W.status,W.assignee??null,JSON.stringify(W.dependsOn??[]),W.summary??null,W.updatedAt.toISOString()]);for(let W of f.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
|
|
682
691
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
683
692
|
ON CONFLICT(team_name, run_id) DO UPDATE SET
|
|
684
693
|
agent_id = excluded.agent_id,
|
|
@@ -690,14 +699,14 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
690
699
|
error = excluded.error,
|
|
691
700
|
lease_owner = excluded.lease_owner,
|
|
692
701
|
heartbeat_at = excluded.heartbeat_at,
|
|
693
|
-
version = team_runs.version + 1`,[Q,W.id,W.agentId,W.taskId??null,W.status,W.message,W.startedAt?W.startedAt.toISOString():null,W.endedAt?W.endedAt.toISOString():null,W.error??null,W.leaseOwner??null,W.heartbeatAt?W.heartbeatAt.toISOString():null]);for(let W of
|
|
702
|
+
version = team_runs.version + 1`,[Q,W.id,W.agentId,W.taskId??null,W.status,W.message,W.startedAt?W.startedAt.toISOString():null,W.endedAt?W.endedAt.toISOString():null,W.error??null,W.leaseOwner??null,W.heartbeatAt?W.heartbeatAt.toISOString():null]);for(let W of f.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
|
|
694
703
|
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
695
704
|
ON CONFLICT(team_name, outcome_id) DO UPDATE SET
|
|
696
705
|
title = excluded.title,
|
|
697
706
|
status = excluded.status,
|
|
698
707
|
schema_json = excluded.schema_json,
|
|
699
708
|
finalized_at = excluded.finalized_at,
|
|
700
|
-
version = team_outcomes.version + 1`,[Q,W.id,W.title,W.status,JSON.stringify({requiredSections:W.requiredSections}),W.finalizedAt?W.finalizedAt.toISOString():null]);for(let W of
|
|
709
|
+
version = team_outcomes.version + 1`,[Q,W.id,W.title,W.status,JSON.stringify({requiredSections:W.requiredSections}),W.finalizedAt?W.finalizedAt.toISOString():null]);for(let W of f.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
|
|
701
710
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
702
711
|
ON CONFLICT(team_name, fragment_id) DO UPDATE SET
|
|
703
712
|
outcome_id = excluded.outcome_id,
|
|
@@ -708,16 +717,16 @@ Caused by: ${f.stack}`;return W}async function Wy(f){return await new Promise(($
|
|
|
708
717
|
status = excluded.status,
|
|
709
718
|
reviewed_by = excluded.reviewed_by,
|
|
710
719
|
reviewed_at = excluded.reviewed_at,
|
|
711
|
-
version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f
|
|
712
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[
|
|
713
|
-
`,"utf8");let
|
|
714
|
-
`,"utf8")}async function
|
|
715
|
-
`,"utf8")}function HK(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function XK(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 AK(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 Sw(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function YK(f,$){return f??$??"openai-chat"}function VK(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function BK(f,$,J){let Q=new Set($?.capabilities??J??[]);if($?.supportsVision)Q.add("images");if($?.supportsAttachments)Q.add("files");if($?.supportsReasoning)Q.add("reasoning");return{id:f,name:$?.name??f,maxTokens:$?.maxTokens,contextWindow:$?.contextWindow,maxInputTokens:$?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function Ew(f,$){for(let[J,Q]of Object.entries($??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;b0.registerModel(f,Z,BK(Z,Q))}}function hw(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function bw(f){return Object.assign({},...b0.resolveProviderModelCatalogKeys(f).map((J)=>b0.getGeneratedModelsForProvider(J)))}function kw(f){let $=f.provider.trim();if(!$||b0.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let Q=b0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=bw($),W=AK(f.capabilities),j=W.length>0?W:void 0,H=f.model?.trim(),X={...Z,...Q?.models??{}};if(H)X[H]=hw(H,X[H],j);let A=Object.keys(X).filter(Boolean),Y=H||A[0];if(!Y)return;let V=YK(f.protocol,Q?.provider.protocol),B=VK(f.client,V,Q?.provider.client);b0.registerProvider({provider:{id:$,name:Q?.provider.name??ZK($),description:Q?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:Y,capabilities:XK(f.capabilities)??Q?.provider.capabilities,source:"file"},models:X})}function V9(f){for(let $ of Object.values(f.providers))kw($.settings)}function P4(f,$){let J=$.models??{};if(!Sw($.provider)){Ew(f,J);return}let Q=AK($.provider.capabilities),Z=Object.entries(J).map(([A,Y])=>({id:Y.id?.trim()||A.trim(),model:Y})).filter(({id:A})=>A.length>0),W=$.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=YK($.provider.protocol,void 0),H=VK($.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:A,model:Y})=>[A,{...BK(A,Y,Q.length>0?Q:void 0),status:"active"}]));b0.registerProvider({provider:{id:f,name:$.provider.name.trim()||ZK(f),protocol:j,client:H,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:W,capabilities:XK($.provider.capabilities),source:"file"},models:X})}function KK(f){let $=w1(f);if(X9.has($))return;let J=L7($);for(let[Q,Z]of Object.entries(J.providers))P4(Q,Z);X9.add($)}async function B9(f){let $=w1(f);if(X9.has($))return;let J=await t2($);for(let[Q,Z]of Object.entries(J.providers))P4(Q,Z);X9.add($)}function Iw(f){return f.apiKey??f.auth?.apiKey}function xw(f){return(f.auth?.accessToken?.trim()??"").length>0}function GK(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function mw(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 gw(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of f)J=J*31+Q.charCodeAt(0)>>>0;return $[J%$.length]}function FK(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>HK($,J))}async function vw(f,$){let J=await q0.getModelsForProvider(f);if(!$)return J;let Q=await JJ(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return Q?.knownModels?{...J,...Q.knownModels}:J}function _7(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function cw(f){if(!f?.length)return;return[...new Set(f)]}function uw(f,$){return cw([...f??[],...$??[]])}function dw(f){let $=f?.popularRank;return typeof $==="number"&&Number.isFinite($)?$:Number.MAX_SAFE_INTEGER}function lw(f){if(!f||typeof f!=="object")return!1;let $=f;return typeof $.path==="string"&&$.path.trim().length>0&&typeof $.label==="string"&&$.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String($.type))}function pw(f){let $=f?.configFields;if(!Array.isArray($))return;return $.filter(lw)}var K9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},PK={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function rw(f){if(!f)return[K9];if(f.source!=="system")return f.baseUrl?[K9,PK]:[K9];let $=[];if(f.env?.length)$.push(K9);if(f.baseUrl)$.push(PK);return $}function iw(f,$){return $.split(".").reduce((J,Q)=>{if(!J||typeof J!=="object")return;return J[Q]},f)}function nw(f){if(typeof f==="string"||typeof f==="number"||typeof f==="boolean"||f===null)return f;return}function aw(f,$,J){if(!f?.length)return;let Q={};for(let Z of f){let j=nw(Z.path==="baseUrl"&&$?.baseUrl===void 0?J?.baseUrl:iw($,Z.path))??Z.defaultValue;if(j!==void 0)Q[Z.path]=j}return Q}function UK(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function O7(f,$){let J=$?.includes("vision")??!1,Q=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function RK(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await C6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function DK(f,$){let J=f.read(),Q=!1;if(J.providers[$])delete J.providers[$],Q=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,Q=!0;if(Q)f.write(J);q0.unregisterProvider($)}async function T7(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=$.baseUrl.trim(),Z=$.apiKey?.trim()??"";if(!Q&&!Z){let P=w1(f);if((await t2(P)).providers[J]){let G=await F9(f,{providerId:J});return{providerId:J,settingsPath:G.settingsPath,modelsPath:G.modelsPath,modelsCount:0}}return DK(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:P,modelsCount:0}}if(q0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=$.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=_7($.models),H=$.modelsSourceUrl?.trim(),X=await RK({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=$.defaultModelId?.trim()&&X.includes($.defaultModelId.trim())?$.defaultModelId.trim():X[0],Y=$.capabilities?.length?[...new Set($.capabilities)]:void 0,V=UK($.headers);f.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:V,timeout:$.timeoutMs,model:A,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=w1(f),K=await t2(B);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:Y,modelsSourceUrl:H},models:O7(X,Y)},await Y9(B,K),P4(J,K.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:X.length}}async function G9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=w1(f),Z=await t2(Q),W=Z.providers[J];if(!W){let M=f.getProviderSettings(J);if(!M)throw Error(`provider "${J}" does not exist`);let L=$.modelsSourceUrl?.trim(),D=_7($.models)[0]??M.model?.trim();if(!D&&!L)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:$.name?.trim()||GK(J),baseUrl:$.baseUrl?.trim()??M.baseUrl?.trim()??"",defaultModelId:D,protocol:M.protocol,client:M.client,capabilities:M.capabilities},models:D?O7([D],M.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=$.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let H=$.baseUrl?.trim()??W.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=$.capabilities===void 0?W.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],A=$.protocol===void 0?W.provider.protocol:$.protocol??void 0,Y=$.client===void 0?W.provider.client:$.client??void 0,V=_7($.models),B=$.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,K=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,P=Object.keys(W.models??{}).map((M)=>M.trim()).filter(Boolean),R=await RK({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:P,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let G=$.defaultModelId===void 0?W.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=G&&R.includes(G)?G:R[0],O={...f.getProviderSettings(J)??{},provider:J,baseUrl:H,model:F};if(A)O.protocol=A;else delete O.protocol;if(Y)O.client=Y;else delete O.client;if($.apiKey!==void 0){let M=$.apiKey?.trim()??"";if(M)O.apiKey=M;else delete O.apiKey}if($.headers!==void 0){let M=UK($.headers);if(M)O.headers=M;else delete O.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")O.timeout=$.timeoutMs;else delete O.timeout;return f.saveProviderSettings(O,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:H,defaultModelId:F,protocol:A,client:Y,capabilities:X,modelsSourceUrl:B},models:O7(R,X)},await Y9(Q,Z),P4(J,Z.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function F9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=w1(f),Z=await t2(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await Y9(Q,Z),q0.unregisterProvider(J),DK(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Q}}async function z7(f){let $=f.read(),J=q0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,H]=await Promise.all([q0.getProvider(W),q0.getModelsForProvider(W)]),X=FK(H),A=$.providers[W]?.settings,Y=j?.name??GK(W),V=uw(j?.capabilities,A?.capabilities),B=pw(j?.metadata)??rw(j);return{provider:{id:W,name:Y,models:X.length,color:gw(W),letter:mw(Y),enabled:Boolean(A),apiKey:A?Iw(A):void 0,oauthAccessTokenPresent:A?xw(A):void 0,baseUrl:A?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:A?.protocol??j?.protocol,client:A?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:aw(B,A,j),modelList:X},rank:dw(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:f.getFilePath()}}async function M7(f,$){let J=f.trim(),Q=await vw(J,$),Z=FK(Q);return{providerId:J,models:Z}}function P9(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function LK(f,$){if(!P9($))return P9(f)?{...f}:void 0;let J=P9(f)?{...f}:{};for(let[Q,Z]of Object.entries($)){if(Z==null||Z===""){delete J[Q];continue}if(P9(Z)){let W=LK(J[Q],Z);if(W&&Object.keys(W).length>0)J[Q]=W;else delete J[Q];continue}J[Q]=Z}return Object.keys(J).length>0?J:void 0}function N7(f,$){let J=$.providerId.trim();if($.enabled===!1){let W=f.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return f.write(W),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let Z={...f.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,W)&&typeof $[W]==="string")if($[W].trim().length===0)delete Z[W];else Z[W]=$[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,W))Z[W]=$[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,W)&&$[W]!=null){let j=LK(Z[W],$[W]);if(j)Z[W]=j;else delete Z[W]}return f.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function q7(f,$){let J=$.trim(),Q=f.getProviderSettings(J),W=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),H=S6(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!H)return{providerId:J,refreshed:!1};let X=await G9(f,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:H,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function y7(f){let $=f.trim().toLowerCase(),J=V0($);if(J)return J.providerId;throw Error(`provider "${f}" does not support OAuth login`)}async function w7(f,$,J,Q){let Z=V0(f);if(!Z)throw Error(`provider "${f}" does not support OAuth login`);let W=P2({onPrompt:async(j)=>j.defaultValue??"",openUrl:J,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return Z.login({settings:$,callbacks:W,telemetry:Q})}function C7(f,$,J,Q,Z){return I$({manager:f,providerId:$,settings:J,credentials:Q,setLastUsed:Z?.setLastUsed})}async function S7(f,$,J,Q){let Z=P2({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});return X8(f,$,{callbacks:Z,telemetry:Q})}function E7(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var OK={};q(OK,{getProviderConfigFields:()=>h7});import*as U9 from"@cline/llms";var tw=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],sw={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function ow(f,$){let J={};for(let Q of tw){let Z=f[Q],W=$[Q];if(Z||W)J[Q]={...Z,...W}}return J}function ew(f){let $=sw[f.providerId];if(!$)return f;return{...f,description:$.description??f.description,fields:$.mode==="replace"?$.fields:ow(f.fields,$.fields)}}var fC=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function $C(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return fC.has(f)}function h7(f){let $=U9.normalizeProviderId(f);if(k$($))return{providerId:$,authMethod:"oauth",fields:{}};let J=U9.MODEL_COLLECTIONS_BY_PROVIDER_ID[$];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:$,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if($C($,J))Z.baseUrl={defaultValue:Q};return ew({providerId:$,authMethod:"api-key",fields:Z})}var NK={};q(NK,{resolveLegacyClineAuth:()=>I7,migrateLegacyProviderSettings:()=>G4});import{existsSync as JC,readFileSync as QC}from"node:fs";import{dirname as ZC,join as b7}from"node:path";import*as D9 from"@cline/llms";import{resolveClineDataDir as WC}from"@cline/shared/storage";var R9="openai",MK=D9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,TK=128000;function I7(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;let Q=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:Q,accountId:J.userInfo?.id}}catch{return}}function S(f){let $=f?.trim();return $?$:void 0}function zK(f){if(!JC(f))return;try{let $=QC(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function jC(f){let $=f.dataDir??WC(),J=f.globalStatePath??b7($,"globalState.json"),Q=f.secretsPath??b7($,"secrets.json"),Z=zK(J),W=zK(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function k7(f){if(f===R9)return MK;return f}function HC(f,$,J,Q){let Z=J==="plan"?"planMode":"actMode",W=$===Q?S(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,H={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[$];return(H?S(typeof f[H]==="string"?f[H]:void 0):void 0)??W}function XC(f,$,J){let Q=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,Z=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,W=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,j=($==="gemini"?Z:void 0)??Q,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function AC(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),Q=S(J.access_token),Z=S(J.refresh_token),W=S(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function YC(f){let $=D9.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function VC(f,$,J,Q){let Z=k7(f),W=S(Q==="plan"?$.planModeApiProvider:$.actModeApiProvider),j=HC($,f,Q,W)??YC(Z),H=XC($,Z,Q),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},Y={};if(f==="openai-codex")Object.assign(Y,AC(J));if(f==="cline")try{let F=S(J["cline:clineAccountId"]);if(F)Y.auth={...Y.auth??{},...I7(F)}}catch{}if(f===R9&&$.openAiHeaders)Y.headers=$.openAiHeaders;if(f==="bedrock"){let F=$.awsAuthentication==="profile"||$.awsUseProfile===!0;Y.aws={accessKey:S(J.awsAccessKey),secretKey:S(J.awsSecretKey),sessionToken:S(J.awsSessionToken),region:S($.awsRegion),authentication:$.awsAuthentication,profile:F?S($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:S($.awsBedrockEndpoint),customModelBaseId:S(Q==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)}}if(f==="vertex")Y.gcp={projectId:S($.vertexProjectId),region:S($.vertexRegion)};if(f===R9&&($.azureApiVersion||$.azureIdentity!==void 0))Y.azure={apiVersion:S($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")Y.sap={clientId:S(J.sapAiCoreClientId),clientSecret:S(J.sapAiCoreClientSecret),tokenUrl:S($.sapAiCoreTokenUrl),resourceGroup:S($.sapAiResourceGroup),deploymentId:S(Q==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){Y.oca={mode:$.ocaMode};let F=S(J.ocaRefreshToken);if(F)Y.auth={...Y.auth??{},refreshToken:F}}if(f==="qwen")Y.apiLine=$.qwenApiLine;if(f==="moonshot")Y.apiLine=$.moonshotApiLine;if(f==="zai")Y.apiLine=$.zaiApiLine;if(f==="minimax")Y.apiLine=$.minimaxApiLine;let V={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=S(A[f]),K=S(V[f]),P={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...Y},R=WJ.safeParse(P);if(!R.success)return;return Object.keys(P).filter((F)=>F!=="provider").length>0?R.data:void 0}function BC(f,$){if(f!==MK)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model,contextWindow:TK,maxInputTokens:TK,capabilities:["streaming","tools","images"]}}}}function KC(f,$){let J=new Set;for(let Z of[f.actModeApiProvider,f.planModeApiProvider]){let W=S(Z);if(W)J.add(W)}if(S($.apiKey))J.add("anthropic");if(S($.openRouterApiKey))J.add("openrouter");if(S($.openAiApiKey))J.add(R9);if(S($.openAiNativeApiKey))J.add("openai-native");if(S($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(S($.geminiApiKey))J.add("gemini");if(S($.ollamaApiKey))J.add("ollama");if(S($.awsAccessKey)||S($.awsBedrockApiKey)||f.awsAuthentication!==void 0||f.awsUseProfile===!0||S(f.awsProfile))J.add("bedrock");if(S(f.vertexProjectId)||S(f.vertexRegion))J.add("vertex");if(S($.clineApiKey))J.add("cline");let Q=I7(S($["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)J.add("cline");if(S($.ocaApiKey))J.add("oca");if(S($.sapAiCoreClientId)||S($.sapAiCoreClientSecret)||S(f.sapAiCoreTokenUrl)||S(f.sapAiCoreBaseUrl)||S(f.sapAiResourceGroup)||f.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function G4(f){let $=f.providerSettingsManager.read(),J=jC(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=KC(Q,Z),H=R$();H.providers={...$.providers},H.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,Y=b7(ZC(f.providerSettingsManager.getFilePath()),"models.json"),V=L7(Y),B=0;for(let R of j){let G=k7(R);if(H.providers[G])continue;let F=VC(R,Q,Z,W);if(!F)continue;H.providers[G]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let U=BC(G,F);if(U&&!V.providers[G])V.providers[G]=U,B+=1}if(A===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let K=S(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),P=K?k7(K):void 0;if(H.lastUsedProvider=$.lastUsedProvider??(P&&H.providers[P]?P:Object.keys(H.providers)[0]),f.providerSettingsManager.write(H),B>0)jK(Y,V);return{migrated:A>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}_0();r5();var qK={};q(qK,{FileTeamPersistenceStore:()=>L9});import{appendFileSync as PC,existsSync as x7,mkdirSync as GC,readFileSync as FC,renameSync as UC,unlinkSync as RC,writeFileSync as DC}from"node:fs";import{join as m7}from"node:path";import{resolveTeamDataDir as LC}from"@cline/shared/storage";function _C(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class L9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=_C(f.teamName),J=f.baseDir?.trim()||LC();this.dirPath=m7(J,$),this.statePath=m7(this.dirPath,"state.json"),this.taskHistoryPath=m7(this.dirPath,"task-history.jsonl")}loadState(){if(!x7(this.statePath))return;try{let f=FC(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return NV($.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`;DC(J,`${JSON.stringify($,null,2)}
|
|
716
|
-
`,"utf8"),
|
|
717
|
-
`,"utf8")}ensureDir(){if(!x7(this.dirPath))GC(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(x7(this.statePath))RC(this.statePath)}}var yK={};q(yK,{ChatViewStateSchema:()=>g7,ChatSummarySchema:()=>M9,ChatSessionStatusSchema:()=>O9,ChatSessionConfigSchema:()=>_9,ChatMessageSchema:()=>z9,ChatMessageRoleSchema:()=>T9});import{z as E}from"zod";var _9=E.object({workspaceRoot:E.string().min(1),cwd:E.string().optional(),provider:E.string().min(1),model:E.string().min(1),mode:E.enum(["act","plan"]).default("act"),apiKey:E.string(),systemPrompt:E.string().optional(),rules:E.string().optional(),maxIterations:E.number().int().positive().optional(),enableTools:E.boolean(),enableSpawn:E.boolean().optional(),enableTeams:E.boolean().optional(),autoApproveTools:E.boolean().optional(),missionStepInterval:E.number().int().positive().optional(),missionTimeIntervalMs:E.number().int().positive().optional()}),O9=E.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),T9=E.enum(["user","assistant","tool","system","status","error"]),z9=E.object({id:E.string().min(1),sessionId:E.string().nullable(),role:T9,content:E.string(),createdAt:E.number().int().nonnegative(),meta:E.object({stream:E.enum(["stdout","stderr"]).optional(),toolName:E.string().optional(),iteration:E.number().int().nonnegative().optional(),agentId:E.string().optional(),conversationId:E.string().optional(),hookEventName:E.string().optional(),inputTokens:E.number().int().nonnegative().optional(),outputTokens:E.number().int().nonnegative().optional(),checkpoint:E.object({ref:E.string(),createdAt:E.number().int().nonnegative(),runCount:E.number().int().positive(),kind:E.enum(["stash","commit"]).optional()}).optional()}).optional()}),M9=E.object({toolCalls:E.number().int().nonnegative(),tokensIn:E.number().int().nonnegative(),tokensOut:E.number().int().nonnegative()}),g7=E.object({sessionId:E.string().nullable(),status:O9,config:_9,messages:E.array(z9),rawTranscript:E.string(),error:E.string().nullable(),summary:M9});var wK={};q(wK,{CORE_BUILD_VERSION:()=>v7});var v7=MY;import{Agent as QS,createAgentRuntime as ZS}from"@cline/agents";var SK={};q(SK,{fetchClineRecommendedModels:()=>c7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>N9});import{getClineEnvironmentConfig as OC}from"@cline/shared";var TC=5000,N9={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 zC(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function CK(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 MC(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],Q=Array.isArray($.free)?$.free:[],Z=J.map(CK).filter((j)=>j!==null),W=Q.map(CK).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function NC(f){let $=f.baseUrl?.trim();if($)return $;let J=OC().apiBaseUrl;try{return(f.providerSettingsManager??new Lf).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function qC(f,$,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await f($,{signal:Q.signal})}finally{clearTimeout(Z)}}async function c7(f={}){try{let $=NC(f),J=f.fetchImpl??fetch,Q=await qC(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??TC);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=MC(Z);if(W)return W}catch{}return zC(N9)}var EK={};q(EK,{loadLlmsConfigFromFile:()=>d7,defineLlmsConfig:()=>u7});import{readFile as yC}from"node:fs/promises";import wC from"node:path";function u7(f){return f}async function d7(f){let $=wC.resolve(f),J=await yC($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${$}": ${W}`)}return CC(Q,$)}function CC(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let Q=f.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}var mK={};q(mK,{createLlmsSdk:()=>p7,DefaultLlmsSdk:()=>F4});import{BUILT_IN_PROVIDER_IDS as kK,createHandler as hC,createHandlerAsync as bC,getProviderCollection as kC,hasProvider as IK,registerAsyncHandler as IC,registerHandler as xC,registerModel as mC,registerProvider as xK}from"@cline/llms";function hK(f){return f?{...f}:{}}function SC(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function EC(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function bK(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 l7{providers=new Map;register(f){EC(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??{},...hK(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:SC(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...hK(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 F4{configuredProviders=new l7;constructor(f){this.applyConfig(f)}createHandler(f){return hC(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return bC(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(xK(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)xC(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)IC(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.`);xK({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){mC(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...kK]}async getBuiltInProviders(){return(await Promise.all(kK.map(($)=>kC($)))).filter(($)=>$!==void 0).map(($)=>bK({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=IK($.id),Q=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,Z=typeof Q==="string"&&IK(Q);if(!J&&!Z)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function p7(f){return new F4(f)}EW();async function gC(){return Promise.resolve().then(() => (f7(),cB))}function AS(){return new Date().toISOString()}function YS(f){if(uK(f)!=="providers.json")return;let $=i7(f);if(uK($)!=="settings")return;return i7($)}class Lf{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??XS(),this.dataDir=f.dataDir??YS(this.filePath),this.dataDir||!f.filePath)G4({providerSettingsManager:this,dataDir:this.dataDir});if(KK(this),V9(this.read()),r7(this.filePath))try{cK(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!r7(this.filePath))return R$();try{let f=jS(this.filePath,"utf8"),$=JSON.parse(f),J=V2.safeParse($);if(J.success)return V9(J.data),J.data}catch{}return R$()}write(f){let $=V2.parse(f),J=i7(this.filePath);if(!r7(J))WS(J,{recursive:!0,mode:448});HS(this.filePath,`${JSON.stringify($,null,2)}
|
|
718
|
-
`,"utf8");try{cK(this.filePath,384)}catch{}V9($)}saveProviderSettings(f,$={}){let J=WJ.parse(f),Q=this.read(),Z=J.provider,W=$.setLastUsed!==!1,j=Q.providers[Z],H=$.tokenSource??j?.tokenSource??"manual",X={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:AS(),tokenSource:H}},lastUsedProvider:W?Z:Q.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 c0(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return c0($,f)}async refreshCatalog(){try{await A2({})}catch{}}}_0();x5();function VS(f,$){let J=f?.expiresAt,Q=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===Q}class q9 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 n7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new Lf,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){let $=V0(f.providerId);if(!$)return null;return this.resolveWithSingleFlight($.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let Q=this.resolveProviderApiKeyInternal(f,$).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,Q),Q}async resolveProviderApiKeyInternal(f,$){let J=V0(f);if(!J)return null;let Q=this.providerSettingsManager.getProviderSettings(J.storageProviderId);if(!Q)return null;let Z=A8(f,Q);if(!Z)return null;let W=await J.refresh({settings:Q,credentials:Z,forceRefresh:$,telemetry:this.telemetry});if(!W)throw new q9(f);let j=I$({manager:this.providerSettingsManager,providerId:f,settings:Q,credentials:W,setLastUsed:!1,save:!1}),H=!VS(Q.auth,j.auth);if(H)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:J.getApiKey(j)??W.access,accountId:W.accountId,refreshed:H}}}import{normalizeUserInput as BS}from"@cline/shared";import{nanoid as KS}from"nanoid";class dK{list(f){return f?s0(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((X)=>X.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:s0(f),updated:!1};let Z=f.pendingPrompts[Q];if(!Z)return{sessionId:$.sessionId,prompts:s0(f),updated:!1};let W=$.prompt===void 0?Z.prompt:BS($.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=$.delivery??Z.delivery,H={...Z,prompt:W,mode:$.mode??Z.mode,delivery:j};return f.pendingPrompts.splice(Q,1),PS(f,H,Q,Z.delivery),{sessionId:$.sessionId,prompts:s0(f),prompt:y9(H),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),Q=f.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:$.sessionId,prompts:s0(f),removed:!1};let[Z]=f.pendingPrompts.splice(Q,1);return{sessionId:$.sessionId,prompts:s0(f),prompt:Z?y9(Z):void 0,removed:!0}}enqueue(f,$){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=$,H=f.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=f.pendingPrompts.splice(H,1),A={...X,prompt:J,mode:Q??X.mode,userImages:W??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")f.pendingPrompts.unshift({...A,delivery:"steer"});else f.pendingPrompts.push(A)}else{let X={id:`pending_${Date.now()}_${KS(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")f.pendingPrompts.unshift(X);else f.pendingPrompts.push(X)}return s0(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if($<0)return{prompts:s0(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:s0(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:s0(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),s0(f)}clear(f){return f.pendingPrompts.length=0,[]}}class a7{deps;service=new dK;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}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:s0(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(!$)return;if($.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront($,J),this.emitPrompts($)}finally{if($.drainingPendingPrompts=!1,Q&&$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=y9($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function y9(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function s0(f){return f.pendingPrompts.map(y9)}function PS(f,$,J,Q){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(Q==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}_0();class s7{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let Q=this.deps.getSession(f),Z={sessionId:f,config:$,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=EQ(J),j=!!Q&&(!W.agentId||W.agentId===t7(Q.agent));hQ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:t7(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(UW(J,$),$.type==="agent_event"){let Q={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};hQ(Q,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let Q=kf({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:t7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(Q)of(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await RW(f,$,this.deps.invokeBackendOptional),J)DW(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 Q=$.payload&&typeof $.payload==="object"?$.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():f,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog(f,$,J){let Q=this.deps.getSession(f),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!$||typeof $!=="object")return;let W=$,j=typeof W.message==="string"?W.message:"";if(!j)return;let H=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(H.sessionId??=f,typeof W.pluginName==="string"&&W.pluginName)H.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,H);return}if(W.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function t7(f){return f.getAgentId()}function o7(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:B$(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 e7(f,$){let J=f[$];return typeof J==="function"?J:null}async function lK(f,$,...J){let Q=e7(f,$);if(!Q)throw Error(`session service method not available: ${$}`);return Promise.resolve(Q.apply(f,J))}async function pK(f,$,...J){let Q=e7(f,$);if(!Q)return;await Promise.resolve(Q.apply(f,J))}async function rK(f,$,...J){let Q=e7(f,$);if(!Q)return;return await Promise.resolve(Q.apply(f,J))}Af();_0();function f3(f,$,J){return{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 W=kf({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(W)of($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...W});f8($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...W}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,W=f.subAgentStarts.get(Q.subAgentId),j=W?Date.now()-W.startedAt:0,H=Q.result?.text?Q.result.text.split(`
|
|
719
|
-
`).length:0;f8($.telemetry,{event:"ended",ulid:J,durationMs:j,outputLines:H,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...kf({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)}}}function $3(f,$,J,Q){let Z=f3(f,$,J);return Y$({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 j=$.enableTools?i$({cwd:$.cwd,...g0[hf({mode:$.mode})],executors:Q}):[];if($.enableSpawnAgent)j.push($3(f,$,J,Q));return t$(j)},...Z})}import{readFile as GS,stat as FS}from"node:fs/promises";var US=20480000;async function iK(f){let $=await FS(f);if(!$.isFile())throw Error("Path is not a file");if($.size>US)throw Error("File is too large to read into context.");let J=await GS(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var nK=5000;function U4(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function MS(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=U4($.inputTokens),Q=U4($.outputTokens),Z=U4($.cacheReadTokens),W=U4($.cacheWriteTokens),j=U4($.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function NS(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 Df{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new gJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new C$;constructor(f){let $=DS();if($)zS($);let J=_1(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new i2,this.createAgentInstance=f.createAgent??((Q)=>new H$(Q)),this.defaultCapabilities=D0(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new Lf,this.oauthTokenManager=f.oauthTokenManager??new n7({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new a7({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new s7({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession(f){let $=f.source??F0.CLI,J=s(),Q=f.config.sessionId?.trim()??"",Z=Q||_S(),W=f,j=W.initialMessages??[],H=j.length>0?o1(j):K0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=J3(X,Z),Y=J3(A,`${Z}.messages.json`),V=J3(A,`${Z}.json`),B=B$(f.config),K=C0.parse({version:1,session_id:Z,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:Y}),P;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let w=await this.invokeOptionalValue("readSessionManifest",Z);if(w)K=w,P={manifestPath:V,messagesPath:w.messages_path||Y,manifest:w}}let G=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:A,rootMessagesPath:P?.messagesPath??Y,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,G);let F=D0(this.defaultCapabilities,f.capabilities),U=F?.toolExecutors??this.toolExecutors,O=f.localRuntime,M=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,D,y={getSession:(w)=>this.sessions.get(w),subAgentStarts:this.subAgentStarts,onAgentEvent:(w,G0,Q0)=>this.eventBridge.dispatchAgentEvent(w,G0,Q0),invokeBackendOptional:(w,...G0)=>this.invokeOptional(w,...G0)};D=await nX({input:W,localRuntime:f.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(w)=>{if(w.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,w.payload,M);return}this.eventBridge.handlePluginEvent(Z,w,L)},onTeamEvent:(w)=>{this.eventBridge.handleTeamEvent(Z,w),D.config.onTeamEvent?.(w)},createSpawnTool:()=>$3(y,D.config,Z,U),createSubAgentLifecycleCallbacks:(w)=>f3(y,w,Z),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(w)=>{await this.persistSessionMetadata(Z,()=>w)}});let b=await this.runtimeBuilder.build(D.runtimeBuilderInput),I=D.config,o=D.providerConfig;if(b.teamRuntime&&!I.teamName?.trim())I.teamName=b.teamRuntime.getTeamName();let Y0=[...b.tools,...I.extraTools??[]],f0=b.extensions??D.extensions,t={sessionId:Z,providerId:o.providerId,modelId:o.modelId,apiKey:o.apiKey,baseUrl:o.baseUrl,headers:o.headers,knownModels:o.knownModels,providerConfig:o,thinking:I.thinking,reasoningEffort:I.reasoningEffort??o.reasoningEffort,systemPrompt:I.systemPrompt,maxIterations:I.maxIterations,execution:I.execution,prepareTurn:G8(I),tools:Y0,hooks:D.hooks,extensions:f0,hookErrorMode:I.hookErrorMode,initialMessages:D.effectiveInput.initialMessages,userFileContentLoader:iK,toolPolicies:D.toolPolicies,requestToolApproval:D.requestToolApproval?async(w)=>{let G0=D.requestToolApproval,Q0=this.sessions.get(Z);if(Q0)await this.markTurnPending(Q0);try{if(!G0)return{approved:!1,reason:"Tool approval callback is not configured."};return await G0(w)}finally{let y0=this.sessions.get(Z);if(y0?.status==="pending")await this.markTurnRunning(y0)}}:void 0,telemetry:I.telemetry,onConsecutiveMistakeLimitReached:I.onConsecutiveMistakeLimitReached,completionPolicy:b.completionPolicy,consumePendingUserMessage:()=>{let w=this.pendingPromptsController.consumeSteer(Z);return w?f4(w.prompt,w.mode??I.mode):void 0},logger:b.logger??I.logger,extensionContext:I.extensionContext,onEvent:(w)=>this.eventBridge.dispatchAgentEvent(Z,I,w)};t.hooks={...t.hooks,onEvent:async(w)=>{if(await D.hooks?.onEvent?.(w),w.type!=="assistant-message")return;let G0=this.sessions.get(Z);if(!G0)return;let Q0=G0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,Q0,I.systemPrompt)}catch(y0){I.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:y0}),C1(I.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:y0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:I.providerId,modelId:I.modelId}})}}};let o0=this.createAgentInstance(t);if(t.onEvent)o0.subscribeEvents(t.onEvent);b.registerLeadAgent?.(o0);let E$=kf({agentId:o0.getAgentId(),conversationId:o0.getConversationId(),teamId:b.teamRuntime?.getTeamId(),teamName:b.teamRuntime?.getTeamName(),teamRole:b.teamRuntime?"lead":void 0});if(tX(I,Z,Q.length>0,B,E$),E$)of(I.telemetry,{ulid:Z,modelId:I.modelId,provider:I.providerId,...E$});if(b.teamRuntime)b4(I.telemetry,{ulid:Z,teamId:b.teamRuntime.getTeamId(),teamName:b.teamRuntime.getTeamName(),leadAgentId:o0.getAgentId(),restoredFromPersistence:b.teamRestoredFromPersistence===!0});let i={sessionId:Z,config:I,sessionMetadata:W.sessionMetadata,...P?{artifacts:P}:{},source:$,startedAt:P?.manifest.started_at??J,updatedAt:P?.manifest.ended_at??P?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:b,agent:o0,started:!1,status:P?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:D.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,i),this.emitStatus(Z,"running"),j.length>0&&!P){if(await this.ensureSessionPersisted(i),await this.invoke("persistSessionMessages",i.sessionId,j,i.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(i,"completed",0)}let _f;try{if(W.prompt?.trim())if(_f=await this.executeTurn(i,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!i.interactive)await this.finalizeSingleRun(i,_f.finishReason);else await this.completeInteractiveTurn(i,_f.finishReason)}catch(w){if(i.interactive&&i.aborting)_f=await this.completeAbortedInteractiveTurn(i);else throw C1(i.config.telemetry,{component:"core",operation:"session.start",error:w,severity:"error",handled:!1,context:{sessionId:i.sessionId,providerId:i.config.providerId,modelId:i.config.modelId}}),await this.failSession(i),w}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:Y,result:_f}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let Q=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),Q=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:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,mode:f.mode,delivery:Q,userImages:f.userImages,userFiles:f.userFiles});return}try{let Z=await this.executeTurn($,{prompt:f.prompt,mode:f.mode,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,Z.finishReason);else await this.completeInteractiveTurn($,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),Z}catch(Z){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw C1($.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.failSession($),Z}}async getAccumulatedUsage(f){let $=pZ(this.usageBySession.get(f)),J=pZ(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&&!J0($.status)){await this.releaseSessionRuntime($,"session_stop");return}if($.interactive&&$.agent.canStartRun()){await this.shutdownSession($,{status:this.resolveInteractiveStopStatus($),exitCode:this.resolveInteractiveStopExitCode($),shutdownReason:"session_stop",endReason:"stopped"});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&&!J0(J.status)?this.releaseSessionRuntime(J,f):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:f,endReason:"disposed"}):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 o7($);let J=f.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return g8(Q);let Z=await this.readManifest(J);return Z?N5(Z):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(g8),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(o7(Z))}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 T$(J.messagesPath);let Q=await this.readManifest($);return T$(Q?.messages_path)}async dispatchHookEvent(f){await UY(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,$),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=Q;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let Z=await this.executeAgentTurn(f,Q,J.userImages,J.userFiles);while(LW(f,Z.finishReason)){let W=await _W(f);if(W.length===0)break;let j=OW(f,W);Z=await this.executeAgentTurn(f,j)}return Z}async completeInteractiveTurn(f,$){if(eJ(f))return;f.lastInteractiveTurnFinishReason=$,await this.markTurnIdle(f),f.aborting=!1}resolveInteractiveStopStatus(f){let $=f.lastInteractiveTurnFinishReason;if(!$)return"cancelled";switch($){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return $}resolveInteractiveStopExitCode(f){return f.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages(),Q=K0();return f.persistedMessages=J,f.started=f.started||J.length>0,this.eventBridge.dispatchAgentEvent(f.sessionId,f.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,Q){let Z=f.started||f.agent.getMessages().length>0,W=f.persistedMessages??f.agent.getMessages(),j=this.usageBySession.get(f.sessionId)??K0(),H=this.aggregateUsageBySession.get(f.sessionId)??j;f.turnUsageBaseline=j,f.turnAggregateUsageBaseline=H,f.turnPrimaryUsage=K0(),f.turnUsageByAgent=new Map,q4(f.config.telemetry,f.sessionId,f.config.mode),b1(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=Z?()=>f.agent.continue($,J,Q):()=>f.agent.run($,J,Q),A=await this.runWithAuthRetry(f,X,W);f.started=!0;let Y=B6(A.messages,A,W);f.persistedMessages=Y;let V=c8(f.turnUsageByAgent?.values()??[]),B=H0(j,A.usage),K=H0(H0(K0(),A.usage),V),P=H0(H,K);return this.usageBySession.set(f.sessionId,B),this.aggregateUsageBySession.set(f.sessionId,P),await this.persistSessionMetadata(f.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:P.totalCost,usage:B,aggregateUsage:P})),await this.invoke("persistSessionMessages",f.sessionId,Y,f.config.systemPrompt),this.observeTaskCompletionTool(f,A),A}catch(X){throw C1(f.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),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((Q)=>Q.name===B0.SUBMIT_AND_EXIT&&Q.error===void 0))return;f.submitAndExitObserved=!0,o2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=B$(f.config),Q=TS($.prompt).trim();if(!Q)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let Z=await u1(Q,J);sX(f.config.telemetry,Z);let W=f4(Z.prompt,$.mode??f.config.mode),j=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:W,userImages:$.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=B$(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 markTurnPending(f){if(f.status==="pending")return;await this.updateStatus(f,"pending",null)}async markTurnIdle(f){if(f.status==="idle")return;await this.updateStatus(f,"idle",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),Q=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,Z=$(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun(f,$){if(eJ(f))return;let J=$==="aborted"||f.aborting,Q=$==="error";await this.shutdownSession(f,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)o2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});v5(f);let J=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),C1(f.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,status:$.status,shutdownReason:$.shutdownReason,providerId:f.config.providerId,modelId:f.config.modelId}})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(Z){Q("update_status",Z)}try{await f.agent.shutdown($.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}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=[],Q=(Z,W)=>{J.push(W),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:Z,error:W,severity:"warn"}),C1(f.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:f.sessionId,stage:Z,reason:$,providerId:f.config.providerId,modelId:f.config.modelId}})};try{await f.agent.shutdown($)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve(f.runtime.shutdown($))}catch(Z){Q("runtime_shutdown",Z)}try{await f.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let Q=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(Z.status=$,J0($))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=Z,f.status=$,f.updatedAt=Q.endedAt??s(),f.endedAt=J0($)?null:Z.ended_at,f.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,Z),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(Q){if(!k$(f.config.providerId)||!OS(Q))throw Q;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(Q){if(Q instanceof q9)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}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(!$){let J=new vf(f);throw C1(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:f,activeSessionCount:this.sessions.size}}),J}return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>LS(Q)?Q:Q3(f,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return kf({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=H0(f.initialUsage,$);return this.withPersistedAggregateUsageFloor(J,f.manifest)}async summarizePersistedTeammateUsage(f,$,J){let Q=Q3($),Z=`${J}.messages.json`,W;try{W=RS(f)}catch{return K0()}let j=K0();for(let H of W){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=Q3(f,H);if(X===Q)continue;let A=await T$(X);if(A.length===0)continue;j=H0(j,o1(A))}return j}withPersistedAggregateUsageFloor(f,$){let J=MS($.metadata?.aggregateUsage);if(J)return NS(f,J);let Q=$.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=f.totalCost)return f;return{...f,totalCost:Q}}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:Pf({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)),nK))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(nK)).find((Q)=>Q.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return lK(this.sessionService,f,...$)}invokeOptional(f,...$){return pK(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return rK(this.sessionService,f,...$)}}function yS(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 wS(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function f9(f={}){let $=new Df({sessionService:new Rf(new Ff),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await $.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:qS(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:wS(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await $.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:yS(Z)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}SS(process.env.CLINE_VCR);function ES(f){let $=process.cwd(),J,Q,Z;for(let W=0;W<f.length;W+=1){let j=f[W],H=f[W+1];if(j==="--cwd"&&H){$=H,W+=1;continue}if(j==="--host"&&H){J=H,W+=1;continue}if(j==="--port"&&H){let X=Number(H);if(Number.isFinite(X))Q=X;W+=1;continue}if(j==="--pathname"&&H)Z=H,W+=1}return{cwd:$,host:J,port:Q,pathname:Z}}async function hS(){let f=ES(process.argv.slice(2));process.chdir(f.cwd);let $=r0({host:f.host,port:f.port,pathname:f.pathname}),J=await q1({host:$.host,port:$.port,pathname:$.pathname,owner:A0(),runtimeHandlers:f9(),cronOptions:{workspaceRoot:f.cwd}}),Q=async()=>{await J.close(),process.exit(0)},Z=!1,W=(j,H)=>{if(Z)return;Z=!0;let X=H instanceof Error?H.stack||H.message:String(H);process.stderr.write(`[hub-daemon] ${j}: ${X}
|
|
720
|
-
`),J.close().catch((
|
|
721
|
-
`)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{Q()}),process.on("SIGTERM",()=>{Q()}),process.on("uncaughtException",(j)=>{W("uncaughtException",j)}),process.on("unhandledRejection",(j)=>{if(j instanceof
|
|
722
|
-
`);return}W("unhandledRejection",j)}),await new Promise(()=>{})}
|
|
720
|
+
version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=f8($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(Q.length===0)return[];let Z=wW();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
721
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function yW($={}){try{let f=new Cf($);return f.init(),f}catch{let f=new L6({teamDir:$.teamDir});return f.init(),f}}function U9($,f){return py($,f)}function iy($,f){let J=f?.["*"]??{},Q=f?.[$]??{};return{...J,...Q}.enabled!==!1}function ny($,f){return $.filter((J)=>iy(J.name,f))}function SW($,f){return s$(ny($,f))}var ay={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function sy($){let f=$.trim().toLowerCase();return ay[f]??f}function ty($,f){if(f.tools===void 0)return $;let J=new Set(f.tools.map(sy));if(f.skills!==void 0)J.add("skills");return $.filter((Q)=>J.has(Q.name))}function L9(){return`team-${ry(5)}`}function z9($,f,J,Q,Z,W,j,X){let Y=c0[b1({mode:J})],V=of(f,Q,J,Z??tf);return SW(i$({cwd:$,...Y,enableSkills:!!j,...V,executors:{...j?{skills:j}:{},...X??{}}}),W)}function oy($){return z9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,ey,$.toolExecutors).some((f)=>f.name==="skills")}var ey=async()=>"";async function $S($){let f=M0();if(!v1({filePath:f}))return{tools:[]};let J=new Af({clientFactory:w2({settingsPath:f})}),Q;try{Q=await Hf(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let Z=Q.filter((X)=>X.disabled!==!0),W=await Promise.allSettled(Z.map((X)=>y2({serverName:X.name,provider:J}))),j=[];for(let[X,Y]of W.entries())if(Y.status==="fulfilled")j.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${V}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function fS($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function JS($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function QS($){let f=c0[b1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class J8{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:B}=$,H=$.onTeamEvent??(()=>{}),A=QS(f),K=f.workspaceRoot??f.cwd,G=$.toolPolicies??f.toolPolicies,R=B1(),P=[],F=f.teamName?.trim()||L9(),D=f.sessionId?.trim()||F,_=A.enableSpawnAgent?x2({workspaceRoot:K}):{configs:[],errors:[]},O=_.configs.some((m)=>m.skills!==void 0),z=U9(V,"rules"),U=U9(V,"skills"),N=U||O,y=U9(V,"workflows"),h=U9(V,"plugins"),u=z||U||y,t=!1,f0=Boolean(Y),o=Y,$1;for(let m of _.errors)(Z??f.logger)?.log?.(`[agents] Failed to load agent config at ${m.path}: ${m.error.message}`);if(!o&&(u||O))o=z$({skills:N?{workspacePath:K,includePluginSkills:h,pluginSkillDirectories:h?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:K},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(o)await o.start().catch(()=>{});let E$=A.enableTools&&U&&Boolean(o)&&o?.hasConfiguredSkills(f.skills)===!0&&oy({cwd:f.cwd,providerId:f.providerId,mode:A.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:G,toolExecutors:B}),n=o&&u?o.createExtension({includeRules:z,includeSkills:U,includeWorkflows:y,registerSkillsTool:E$,allowedSkillNames:f.skills}):void 0,_1=n?[...Q??f.extensions??[],n]:Q??f.extensions;if(A.enableTools){if(P.push(...z9(f.cwd,f.providerId,A.mode,f.modelId,f.toolRoutingRules,G,void 0,B)),!A.disableMcpSettingsTools){let m=await $S(f.logger);P.push(...m.tools),$1=m.shutdown}}let S,G0=A.enableAgentTeams?yW():void 0,j0=G0?.loadRuntime(D),w0=j0?.state,bf=j0?.teammates??[],O1=new Map(bf.map((m)=>[m.agentId,m])),X1=f.sessionId||F,j8,kf=[],N6=!1,M1=V$({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:_1,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(A.enableSpawnAgent){if(_.configs.length>0)P.push(...SW(g2({configProvider:M1,agents:_.configs,createSubAgentTools:(m)=>A.enableTools?ty(z9(f.cwd,m.providerId??f.providerId,A.mode,m.modelId??f.modelId,f.toolRoutingRules,G,m.skills!==void 0&&o?.createSkillsExecutor?o.createSkillsExecutor(m.skills):void 0,B),m):[],hookErrorMode:f.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(X1))this.teamRuntimeEntries.set(X1,{delegatedAgentConfigProvider:M1});let q6=()=>{if(!A.enableAgentTeams)return;let m=this.teamRuntimeEntries.get(X1)??{delegatedAgentConfigProvider:M1};if(this.teamRuntimeEntries.set(X1,m),S=m.runtime,!S){if(S=new Of({teamName:F,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(J0)=>{if(H(J0),S&&G0){if(J0.type==="teammate_spawned"&&J0.teammate?.rolePrompt){let T1={agentId:J0.agentId,rolePrompt:J0.teammate.rolePrompt,modelId:J0.teammate.modelId,maxIterations:J0.teammate.maxIterations};O1.set(T1.agentId,T1)}if(J0.type==="teammate_shutdown"&&!JS(J0.reason))O1.delete(J0.agentId);G0.handleTeamEvent(D,J0),G0.persistRuntime(D,S.exportState(),Array.from(O1.values()))}}}),w0)S.hydrateState(w0),N6=!0;m.runtime=S}if(!t){if(!S)return;t=!0;let J0=f2({runtime:S,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(w0),restoredTeammates:bf,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(T1)=>{kf=T1,j8?.addTools(T1)},createBaseTools:A.enableTools?()=>z9(f.cwd,f.providerId,A.mode,f.modelId,f.toolRoutingRules,G,void 0,B):void 0,teammateConfigProvider:M1});if(N6)S.recoverActiveRuns("runtime_recovered");if(J0.restoredFromPersistence)X?.();P.push(...J0.tools)}return S};if(A.enableSpawnAgent&&j){let m=j();P.push({...m,execute:async(J0,T1)=>{return q6(),m.execute(J0,T1)}})}if(A.enableAgentTeams)q6();let If=SW(P,G),l9=If.some((m)=>m.name==="submit_and_exit"&&m.lifecycle?.completesRun===!0),w6=A.enableAgentTeams?()=>{let m=this.teamRuntimeEntries.get(X1)?.runtime;if(!m)return;let J0=m.listTasks(),T1=J0.some((t1)=>t1.status==="in_progress"||t1.status==="pending"),N3=m.listRuns({}),gG=N3.some((t1)=>t1.status==="running"||t1.status==="queued");if(T1||gG){let t1=J0.filter((x0)=>x0.status==="in_progress"||x0.status==="pending").map((x0)=>`${x0.id} (${x0.status}): ${x0.title}`).join(", "),q3=N3.filter((x0)=>x0.status==="running"||x0.status==="queued").map((x0)=>`${x0.id} (${x0.status})`).join(", "),p9=[];if(t1)p9.push(`Unfinished tasks: ${t1}`);if(q3)p9.push(`Active runs: ${q3}`);return`[SYSTEM] You still have team obligations. ${p9.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,xG=l9?{requireCompletionTool:!0,...w6?{completionGuard:w6}:{}}:w6?{completionGuard:w6}:void 0;return{tools:If,logger:Z??f.logger,telemetry:W??f.telemetry,teamRuntime:S,teamRestoredFromPersistence:Boolean(w0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(X1)?.delegatedAgentConfigProvider??M1,extensions:_1,completionPolicy:xG,registerLeadAgent:(m)=>{if(j8=m,kf.length>0)m.addTools(s$(kf,[...R]))},shutdown:async(m)=>{if(fS(S,m),this.teamRuntimeEntries.delete(X1),await $1?.(),!f0)o?.stop()}}}}var mK={};w(mK,{requestDesktopToolApproval:()=>EW});import{mkdir as ZS,readFile as WS,unlink as jS,writeFile as XS}from"node:fs/promises";import{join as gK}from"node:path";function YS($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function VS($){return new Promise((f)=>setTimeout(f,$))}async function CW($){try{await jS($)}catch{}}async function EW($,f={}){let J=f.approvalDir?.trim(),Q=f.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await ZS(J,{recursive:!0});let Z=YS(`${$.toolCallId}`),W=gK(J,`${Q}.request.${Z}.json`),j=gK(J,`${Q}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await XS(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
|
|
722
|
+
`,"utf8");let Y=f.timeoutMs??300000,V=f.pollIntervalMs??200,B=Date.now();while(Date.now()-B<Y){try{let H=await WS(j,"utf8"),A=JSON.parse(H),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([CW(j),CW(W)]),K}catch{}await VS(V)}return await CW(W),{approved:!1,reason:"Tool approval request timed out"}}H1();H1();var dK={};w(dK,{uninstallPlugin:()=>vW});import{existsSync as Z8,readdirSync as BS,readFileSync as HS,rmdirSync as AS,rmSync as KS,statSync as GS}from"node:fs";import{basename as o0,dirname as C$,extname as FS,isAbsolute as PS,join as s1,relative as DS,resolve as Q8,sep as hW}from"node:path";import{discoverPluginModulePaths as RS,resolvePluginConfigSearchPaths as US}from"@cline/shared/storage";var gW="_installed",zS="package",LS=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function bW($){return $.trim().toLowerCase()}function j1($,f){let J=f?.trim();if(!J)return;$.add(J)}function _S($){return $.replace(/-[0-9a-f]{12}$/i,"")}function kW($){let f=FS($);return f?$.slice(0,-f.length):$}function IW($){if(!Z8($))return;try{let f=JSON.parse(HS($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function mW($,f){let J=DS(f,$);return J===""||!J.startsWith("..")&&!PS(J)}function vK($){let J=Q8($).split(hW),Q=J.lastIndexOf(gW);if(Q<0)return;let Z=J[Q+1];if(!Z)return;let W=LS.get(Z)??1,j=Q+2+W;if(J.length<j)return;let X=J.slice(0,j).join(hW)||hW;return Z8(X)?X:void 0}function _9($){try{return BS($,{withFileTypes:!0})}catch{return[]}}function OS($){let f=s1($,gW);if(!Z8(f))return[];let J=[];for(let Q of _9(f)){if(!Q.isDirectory())continue;let Z=s1(f,Q.name);if(Q.name==="git"){for(let W of _9(Z)){if(!W.isDirectory())continue;let j=s1(Z,W.name);for(let X of _9(j))if(X.isDirectory())J.push(s1(j,X.name))}continue}for(let W of _9(Z))if(W.isDirectory())J.push(s1(Z,W.name))}return J.sort((Q,Z)=>Q.localeCompare(Z))}function cK($){try{return RS($)}catch{return[]}}function xW($){let f=cK($),J=new Set;j1(J,o0($)),j1(J,_S(o0($))),j1(J,IW(s1($,"package.json"))),j1(J,IW(s1($,zS,"package.json")));for(let Q of f)j1(J,o0(Q)),j1(J,kW(o0(Q)));return{installPath:$,entryPaths:f,names:[...J].sort((Q,Z)=>Q.localeCompare(Z)),installed:!0}}function MS($,f){let J=Q8($),Q=f.find((j)=>mW(J,j));if(!Q)return;let Z=C$(J);while(Z!==Q&&Z!==C$(Z)){if(Z8(s1(Z,"package.json")))return Z;Z=C$(Z)}let W=o0(J);if((W==="index.ts"||W==="index.js")&&C$(J)!==Q)return C$(J);return J}function uK($,f){let J=MS($,f);if(!J)return;let Q=new Set;return j1(Q,o0($)),j1(Q,kW(o0($))),j1(Q,o0(J)),j1(Q,kW(o0(J))),j1(Q,IW(s1(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!1}}function TS($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return US(f).filter((J)=>Z8(J))}function NS($){let f=new Map;for(let J of $){for(let Q of OS(J))f.set(Q,xW(Q));for(let Q of cK(J)){let Z=vK(Q);if(Z){if(!f.has(Z))f.set(Z,xW(Z));continue}let W=uK(Q,$);if(W)f.set(W.installPath,W)}}return[...f.values()].sort((J,Q)=>J.installPath.localeCompare(Q.installPath))}function qS($,f){let J=bW(f);if(!J)return!1;if(bW($.installPath)===J)return!0;return $.names.some((Q)=>bW(Q)===J)}function wS($,f,J){let Q=Q8($);for(let W of f){if(mW(Q,W.installPath))return W;if(W.entryPaths.some((j)=>Q8(j)===Q))return W}let Z=vK(Q);if(Z)return xW(Z);if(Z8(Q))return uK(Q,J);return}function yS($){let f=O0(),J=f.disabledPlugins;if(!J?.length)return;let Q=J.filter((Z)=>{let W=Q8(Z);if(mW(W,$.installPath))return!1;return!$.entryPaths.some((j)=>Q8(j)===W)});if(Q.length===J.length)return;x1({...f,disabledPlugins:Q})}function SS($){let f=C$($);while(f!==C$(f)&&o0(f)!==gW){try{AS(f)}catch{return}f=C$(f)}}function CS($){return`${$.names[0]??o0($.installPath)} at ${$.installPath}`}async function vW($){let f=TS($),J=NS(f),Q=$.path?.trim(),Z=$.name?.trim(),W;if(Q){if(W=wS(Q,J,f),!W)throw Error(`No plugin found at ${Q}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let X=J.filter((Y)=>qS(Y,Z));if(X.length===0)throw Error(`No plugin found matching "${Z}"`);if(X.length>1)throw Error(`Multiple plugins match "${Z}": ${X.map(CS).join(", ")}`);W=X[0]}let j=GS(W.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${W.installPath}`);if(KS(W.installPath,{recursive:j.isDirectory(),force:!0}),yS(W),W.installed)SS(W.installPath);return{name:Z||W.names[0]||o0(W.installPath),installPath:W.installPath,removedPaths:[W.installPath],entryPaths:W.entryPaths}}var VG={};w(VG,{updateLocalProvider:()=>S9,saveLocalProviderSettings:()=>nW,saveLocalProviderOAuthCredentials:()=>oW,resolveLocalClineAuthToken:()=>$3,refreshProviderModelsFromSource:()=>aW,normalizeOAuthProvider:()=>sW,loginLocalProvider:()=>tW,loginAndSaveLocalProviderOAuthCredentials:()=>eW,listLocalProviders:()=>rW,getLocalProviderModels:()=>iW,ensureCustomProvidersLoaded:()=>q9,deleteLocalProvider:()=>C9,addLocalProvider:()=>pW});import*as q0 from"@cline/llms";import{existsSync as ES,mkdirSync as hS,readFileSync as bS,writeFileSync as kS}from"node:fs";import{mkdir as IS,readFile as xS,writeFile as gS}from"node:fs/promises";import{dirname as cW,join as mS}from"node:path";import*as I0 from"@cline/llms";import{ModelCapabilitySchema as vS,ProviderCapabilitySchema as cS,ProviderClientSchema as uS,ProviderProtocolSchema as dS}from"@cline/shared";import{z as i}from"zod";var lS=i.object({id:i.string().optional(),name:i.string().optional(),maxTokens:i.number().optional(),contextWindow:i.number().optional(),maxInputTokens:i.number().optional(),capabilities:i.array(vS).optional(),supportsVision:i.boolean().optional(),supportsAttachments:i.boolean().optional(),supportsReasoning:i.boolean().optional()}).passthrough(),pS=i.object({name:i.string(),baseUrl:i.string(),defaultModelId:i.string().optional(),protocol:dS.optional(),client:uS.optional(),capabilities:i.array(cS).optional(),modelsSourceUrl:i.string().optional()}).passthrough(),lK=i.object({provider:pS.optional(),models:i.record(i.string(),lS).optional()}).passthrough(),pK=i.object({version:i.literal(1),providers:i.record(i.string(),lK)}),rS=i.object({version:i.literal(1),providers:i.record(i.string(),i.unknown())}),O9=new Set;function rK($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function Ef($){return mS(cW($.getFilePath()),"models.json")}function M9(){return{version:1,providers:{}}}function iK($){let f=rS.safeParse($);if(!f.success)return M9();let J={};for(let[Q,Z]of Object.entries(f.data.providers)){let W=lK.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function uW($){if(!ES($))return M9();try{let f=bS($,"utf8");return iK(JSON.parse(f))}catch{}return M9()}async function W8($){try{let f=await xS($,"utf8");return iK(JSON.parse(f))}catch{}return M9()}function nK($,f){hS(cW($),{recursive:!0});let J=pK.parse(f);kS($,`${JSON.stringify(J,null,2)}
|
|
723
|
+
`,"utf8")}async function T9($,f){await IS(cW($),{recursive:!0});let J=pK.parse(f);await gS($,`${JSON.stringify(J,null,2)}
|
|
724
|
+
`,"utf8")}function aK($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function sK($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function tK($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function iS($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function oK($,f){return $??f??"openai-chat"}function eK($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function $G($,f,J){let Q=new Set(f?.capabilities??J??[]);if(f?.supportsVision)Q.add("images");if(f?.supportsAttachments)Q.add("files");if(f?.supportsReasoning)Q.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function nS($,f){for(let[J,Q]of Object.entries(f??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;I0.registerModel($,Z,$G(Z,Q))}}function aS($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function sS($){return Object.assign({},...I0.resolveProviderModelCatalogKeys($).map((J)=>I0.getGeneratedModelsForProvider(J)))}function tS($){let f=$.provider.trim();if(!f||I0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let Q=I0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=sS(f),W=tK($.capabilities),j=W.length>0?W:void 0,X=$.model?.trim(),Y={...Z,...Q?.models??{}};if(X)Y[X]=aS(X,Y[X],j);let V=Object.keys(Y).filter(Boolean),B=X||V[0];if(!B)return;let H=oK($.protocol,Q?.provider.protocol),A=eK($.client,H,Q?.provider.client);I0.registerProvider({provider:{id:f,name:Q?.provider.name??rK(f),description:Q?.provider.description,protocol:H,client:A,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:B,capabilities:sK($.capabilities)??Q?.provider.capabilities,source:"file"},models:Y})}function N9($){for(let f of Object.values($.providers))tS(f.settings)}function _6($,f){let J=f.models??{};if(!iS(f.provider)){nS($,J);return}let Q=tK(f.provider.capabilities),Z=Object.entries(J).map(([V,B])=>({id:B.id?.trim()||V.trim(),model:B})).filter(({id:V})=>V.length>0),W=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=oK(f.provider.protocol,void 0),X=eK(f.provider.client,j,void 0),Y=Object.fromEntries(Z.map(({id:V,model:B})=>[V,{...$G(V,B,Q.length>0?Q:void 0),status:"active"}]));I0.registerProvider({provider:{id:$,name:f.provider.name.trim()||rK($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:W,capabilities:sK(f.provider.capabilities),source:"file"},models:Y})}function fG($){let f=Ef($);if(O9.has(f))return;let J=uW(f);for(let[Q,Z]of Object.entries(J.providers))_6(Q,Z);O9.add(f)}async function q9($){let f=Ef($);if(O9.has(f))return;let J=await W8(f);for(let[Q,Z]of Object.entries(J.providers))_6(Q,Z);O9.add(f)}var oS="cline-pass";function eS($){return $.apiKey??$.auth?.apiKey}function $C($){return($.auth?.accessToken?.trim()??"").length>0}function QG($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function fC($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function JC($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of $)J=J*31+Q.charCodeAt(0)>>>0;return f[J%f.length]}function ZG($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>aK(f,J))}async function QC($,f){let J=await q0.getModelsForProvider($);if(!f)return J;let Q=await K4($,{loadPrivateOnAuth:!0,failOnError:!1},f);return Q?.knownModels?{...J,...Q.knownModels}:J}function dW($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function ZC($){if(!$?.length)return;return[...new Set($)]}function WC($,f){return ZC([...$??[],...f??[]])}function jC($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function XC($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function YC($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(XC)}var w9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},JG={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function VC($){if(!$)return[w9];if($.source!=="system")return $.baseUrl?[w9,JG]:[w9];let f=[];if($.env?.length)f.push(w9);if($.baseUrl)f.push(JG);return f}function BC($,f){return f.split(".").reduce((J,Q)=>{if(!J||typeof J!=="object")return;return J[Q]},$)}function HC($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function AC($,f,J){if(!$?.length)return;let Q={};for(let Z of $){let j=HC(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:BC(f,Z.path))??Z.defaultValue;if(j!==void 0)Q[Z.path]=j}return Q}function WG($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function lW($,f){let J=f?.includes("vision")??!1,Q=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function jG($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await vJ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function XG($,f){let J=$.read(),Q=!1;if(J.providers[f])delete J.providers[f],Q=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,Q=!0;if(Q)$.write(J);q0.unregisterProvider(f)}async function pW($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!Q&&!Z){let G=Ef($);if((await W8(G)).providers[J]){let P=await C9($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return XG($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(q0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=f.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=dW(f.models),X=f.modelsSourceUrl?.trim(),Y=await jG({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=f.defaultModelId?.trim()&&Y.includes(f.defaultModelId.trim())?f.defaultModelId.trim():Y[0],B=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,H=WG(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:H,timeout:f.timeoutMs,model:V,protocol:f.protocol,client:f.client},{setLastUsed:!1});let A=Ef($),K=await W8(A);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:V,protocol:f.protocol,client:f.client,capabilities:B,modelsSourceUrl:X},models:lW(Y,B)},await T9(A,K),_6(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function S9($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=Ef($),Z=await W8(Q),W=Z.providers[J];if(!W){let O=$.getProviderSettings(J);if(!O)throw Error(`provider "${J}" does not exist`);let z=f.modelsSourceUrl?.trim(),U=dW(f.models)[0]??O.model?.trim();if(!U&&!z)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:f.name?.trim()||QG(J),baseUrl:f.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:U,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:U?lW([U],O.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??W.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=f.capabilities===void 0?W.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],V=f.protocol===void 0?W.provider.protocol:f.protocol??void 0,B=f.client===void 0?W.provider.client:f.client??void 0,H=dW(f.models),A=f.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!A,G=Object.keys(W.models??{}).map((O)=>O.trim()).filter(Boolean),R=await jG({providerId:J,explicitModels:H,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?W.provider.defaultModelId?.trim():f.defaultModelId?.trim(),F=P&&R.includes(P)?P:R[0],_={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:F};if(V)_.protocol=V;else delete _.protocol;if(B)_.client=B;else delete _.client;if(f.apiKey!==void 0){let O=f.apiKey?.trim()??"";if(O)_.apiKey=O;else delete _.apiKey}if(f.headers!==void 0){let O=WG(f.headers);if(O)_.headers=O;else delete _.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")_.timeout=f.timeoutMs;else delete _.timeout;return $.saveProviderSettings(_,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:F,protocol:V,client:B,capabilities:Y,modelsSourceUrl:A},models:lW(R,Y)},await T9(Q,Z),_6(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function C9($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=Ef($),Z=await W8(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await T9(Q,Z),q0.unregisterProvider(J),XG($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q}}async function rW($,f={}){let J=$.read(),Q=q0.getProviderIds(),Z=await Promise.all(Q.map(async(j)=>{let[X,Y]=await Promise.all([q0.getProvider(j),q0.getModelsForProvider(j)]),V=ZG(Y),B=J.providers[j]?.settings,H=X?.name??QG(j),A=WC(X?.capabilities,B?.capabilities),K=YC(X?.metadata)??VC(X);return{provider:{id:j,name:H,models:V.length,color:JC(j),letter:fC(H),enabled:Boolean(B),apiKey:B?eS(B):void 0,oauthAccessTokenPresent:B?$C(B):void 0,baseUrl:B?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:B?.protocol??X?.protocol,client:B?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:AC(K,B,X),modelList:V},rank:jC(X?.metadata)}}));Z.sort((j,X)=>{if(j.rank!==X.rank)return j.rank-X.rank;return j.provider.name.localeCompare(X.provider.name)||j.provider.id.localeCompare(X.provider.id)});let W=Z.map((j)=>j.provider);if(f.isClinePassEnabled!==!0)W=W.filter((j)=>j.id!==oS);return{providers:W,settingsPath:$.getFilePath()}}async function iW($,f){let J=$.trim(),Q=await QC(J,f),Z=ZG(Q);return{providerId:J,models:Z}}function y9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function YG($,f){if(!y9(f))return y9($)?{...$}:void 0;let J=y9($)?{...$}:{};for(let[Q,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[Q];continue}if(y9(Z)){let W=YG(J[Q],Z);if(W&&Object.keys(W).length>0)J[Q]=W;else delete J[Q];continue}J[Q]=Z}return Object.keys(J).length>0?J:void 0}function nW($,f){let J=f.providerId.trim();if(f.enabled===!1){let W=$.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return $.write(W),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,W)&&typeof f[W]==="string")if(f[W].trim().length===0)delete Z[W];else Z[W]=f[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,W))Z[W]=f[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,W)&&f[W]!=null){let j=YG(Z[W],f[W]);if(j)Z[W]=j;else delete Z[W]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function aW($,f){let J=f.trim(),Q=$.getProviderSettings(J),W=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),X=cJ(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!X)return{providerId:J,refreshed:!1};let Y=await S9($,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:X,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:Y.modelsCount}}function sW($){let f=$.trim().toLowerCase(),J=Q0(f);if(J)return J.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function tW($,f,J,Q){let Z=Q0($);if(!Z)throw Error(`provider "${$}" does not support OAuth login`);let W=_2({onPrompt:async(j)=>j.defaultValue??"",openUrl:J,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return Z.login({settings:f,callbacks:W,telemetry:Q})}function oW($,f,J,Q,Z){return I$({manager:$,providerId:f,settings:J,credentials:Q,setLastUsed:Z?.setLastUsed})}async function eW($,f,J,Q){let Z=_2({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});return D8($,f,{callbacks:Z,telemetry:Q})}function $3($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var BG={};w(BG,{getProviderConfigFields:()=>f3});import*as E9 from"@cline/llms";var KC=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],GC={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function FC($,f){let J={};for(let Q of KC){let Z=$[Q],W=f[Q];if(Z||W)J[Q]={...Z,...W}}return J}function PC($){let f=GC[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:FC($.fields,f.fields)}}var DC=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function RC($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return DC.has($)}function f3($){let f=E9.normalizeProviderId($);if(k$(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=E9.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(RC(f,J))Z.baseUrl={defaultValue:Q};return PC({providerId:f,authMethod:"api-key",fields:Z})}var GG={};w(GG,{resolveLegacyClineAuth:()=>Z3,migrateLegacyProviderSettings:()=>O6});import{existsSync as UC,readFileSync as zC}from"node:fs";import{dirname as LC,join as J3}from"node:path";import*as b9 from"@cline/llms";import{resolveClineDataDir as _C}from"@cline/shared/storage";var h9="openai",KG=b9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,HG=128000;function Z3($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let Q=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:Q,accountId:J.userInfo?.id}}catch{return}}function E($){let f=$?.trim();return f?f:void 0}function AG($){if(!UC($))return;try{let f=zC($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function OC($){let f=$.dataDir??_C(),J=$.globalStatePath??J3(f,"globalState.json"),Q=$.secretsPath??J3(f,"secrets.json"),Z=AG(J),W=AG(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function Q3($){if($===h9)return KG;return $}function MC($,f,J,Q){let Z=J==="plan"?"planMode":"actMode",W=f===Q?E(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?E(typeof $[X]==="string"?$[X]:void 0):void 0)??W}function TC($,f,J){let Q=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,W=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??Q,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,Y=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function NC($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),Q=E(J.access_token),Z=E(J.refresh_token),W=E(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function qC($){let f=b9.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function wC($,f,J,Q){let Z=Q3($),W=E(Q==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=MC(f,$,Q,W)??qC(Z),X=TC(f,Z,Q),Y=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,V={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},B={};if($==="openai-codex")Object.assign(B,NC(J));if($==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)B.auth={...B.auth??{},...Z3(F)}}catch{}if($===h9&&f.openAiHeaders)B.headers=f.openAiHeaders;if($==="bedrock"){let F=f.awsAuthentication==="profile"||f.awsUseProfile===!0;B.aws={accessKey:E(J.awsAccessKey),secretKey:E(J.awsSecretKey),sessionToken:E(J.awsSessionToken),region:E(f.awsRegion),authentication:f.awsAuthentication,profile:F?E(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:E(f.awsBedrockEndpoint),customModelBaseId:E(Q==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")B.gcp={projectId:E(f.vertexProjectId),region:E(f.vertexRegion)};if($===h9&&(f.azureApiVersion||f.azureIdentity!==void 0))B.azure={apiVersion:E(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")B.sap={clientId:E(J.sapAiCoreClientId),clientSecret:E(J.sapAiCoreClientSecret),tokenUrl:E(f.sapAiCoreTokenUrl),resourceGroup:E(f.sapAiResourceGroup),deploymentId:E(Q==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){B.oca={mode:f.ocaMode};let F=E(J.ocaRefreshToken);if(F)B.auth={...B.auth??{},refreshToken:F}}if($==="qwen")B.apiLine=f.qwenApiLine;if($==="moonshot")B.apiLine=f.moonshotApiLine;if($==="zai")B.apiLine=f.zaiApiLine;if($==="minimax")B.apiLine=f.minimaxApiLine;let H={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},A=E(V[$]),K=E(H[$]),G={provider:Z,...A?{apiKey:A}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...B},R=R2.safeParse(G);if(!R.success)return;return Object.keys(G).filter((F)=>F!=="provider").length>0?R.data:void 0}function yC($,f){if($!==KG)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:HG,maxInputTokens:HG,capabilities:["streaming","tools","images"]}}}}function SC($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let W=E(Z);if(W)J.add(W)}if(E(f.apiKey))J.add("anthropic");if(E(f.openRouterApiKey))J.add("openrouter");if(E(f.openAiApiKey))J.add(h9);if(E(f.openAiNativeApiKey))J.add("openai-native");if(E(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(E(f.geminiApiKey))J.add("gemini");if(E(f.ollamaApiKey))J.add("ollama");if(E(f.awsAccessKey)||E(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||E($.awsProfile))J.add("bedrock");if(E($.vertexProjectId)||E($.vertexRegion))J.add("vertex");if(E(f.clineApiKey))J.add("cline");let Q=Z3(E(f["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)J.add("cline");if(E(f.ocaApiKey))J.add("oca");if(E(f.sapAiCoreClientId)||E(f.sapAiCoreClientSecret)||E($.sapAiCoreTokenUrl)||E($.sapAiCoreBaseUrl)||E($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function O6($){let f=$.providerSettingsManager.read(),J=OC($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=SC(Q,Z),X=U$();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let Y=new Date().toISOString(),V=0,B=J3(LC($.providerSettingsManager.getFilePath()),"models.json"),H=uW(B),A=0;for(let R of j){let P=Q3(R);if(X.providers[P])continue;let F=wC(R,Q,Z,W);if(!F)continue;X.providers[P]={settings:F,updatedAt:Y,tokenSource:"migration"},V+=1;let D=yC(P,F);if(D&&!H.providers[P])H.providers[P]=D,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=E(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),G=K?Q3(K):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)nK(B,H);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}F9();L0();W9();var FG={};w(FG,{FileTeamPersistenceStore:()=>k9});import{appendFileSync as CC,existsSync as W3,mkdirSync as EC,readFileSync as hC,renameSync as bC,unlinkSync as kC,writeFileSync as IC}from"node:fs";import{join as j3}from"node:path";import{resolveTeamDataDir as xC}from"@cline/shared/storage";function gC($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class k9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=gC($.teamName),J=$.baseDir?.trim()||xC();this.dirPath=j3(J,f),this.statePath=j3(this.dirPath,"state.json"),this.taskHistoryPath=j3(this.dirPath,"task-history.jsonl")}loadState(){if(!W3(this.statePath))return;try{let $=hC(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return WA(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;IC(J,`${JSON.stringify(f,null,2)}
|
|
725
|
+
`,"utf8"),bC(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),CC(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
|
|
726
|
+
`,"utf8")}ensureDir(){if(!W3(this.dirPath))EC(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(W3(this.statePath))kC(this.statePath)}}var PG={};w(PG,{ChatViewStateSchema:()=>X3,ChatSummarySchema:()=>v9,ChatSessionStatusSchema:()=>x9,ChatSessionConfigSchema:()=>I9,ChatMessageSchema:()=>m9,ChatMessageRoleSchema:()=>g9});import{z as b}from"zod";var I9=b.object({workspaceRoot:b.string().min(1),cwd:b.string().optional(),provider:b.string().min(1),model:b.string().min(1),mode:b.enum(["act","plan"]).default("act"),apiKey:b.string(),systemPrompt:b.string().optional(),rules:b.string().optional(),maxIterations:b.number().int().positive().optional(),enableTools:b.boolean(),enableSpawn:b.boolean().optional(),enableTeams:b.boolean().optional(),autoApproveTools:b.boolean().optional(),missionStepInterval:b.number().int().positive().optional(),missionTimeIntervalMs:b.number().int().positive().optional()}),x9=b.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),g9=b.enum(["user","assistant","tool","system","status","error"]),m9=b.object({id:b.string().min(1),sessionId:b.string().nullable(),role:g9,content:b.string(),createdAt:b.number().int().nonnegative(),meta:b.object({stream:b.enum(["stdout","stderr"]).optional(),toolName:b.string().optional(),iteration:b.number().int().nonnegative().optional(),agentId:b.string().optional(),conversationId:b.string().optional(),hookEventName:b.string().optional(),inputTokens:b.number().int().nonnegative().optional(),outputTokens:b.number().int().nonnegative().optional(),checkpoint:b.object({ref:b.string(),createdAt:b.number().int().nonnegative(),runCount:b.number().int().positive(),kind:b.enum(["stash","commit"]).optional()}).optional()}).optional()}),v9=b.object({toolCalls:b.number().int().nonnegative(),tokensIn:b.number().int().nonnegative(),tokensOut:b.number().int().nonnegative()}),X3=b.object({sessionId:b.string().nullable(),status:x9,config:I9,messages:b.array(m9),rawTranscript:b.string(),error:b.string().nullable(),summary:v9});var DG={};w(DG,{CORE_BUILD_VERSION:()=>Y3});var Y3=$H;import{Agent as _E,createAgentRuntime as OE}from"@cline/agents";var UG={};w(UG,{fetchClineRecommendedModels:()=>V3,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>c9});import{getClineEnvironmentConfig as mC}from"@cline/shared";var vC=5000,c9={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 cC($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function RG($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function uC($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],Q=Array.isArray(f.free)?f.free:[],Z=J.map(RG).filter((j)=>j!==null),W=Q.map(RG).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function dC($){let f=$.baseUrl?.trim();if(f)return f;let J=mC().apiBaseUrl;try{return($.providerSettingsManager??new L1).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function lC($,f,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await $(f,{signal:Q.signal})}finally{clearTimeout(Z)}}async function V3($={}){try{let f=dC($),J=$.fetchImpl??fetch,Q=await lC(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??vC);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=uC(Z);if(W)return W}catch{}return cC(c9)}var zG={};w(zG,{loadLlmsConfigFromFile:()=>H3,defineLlmsConfig:()=>B3});import{readFile as pC}from"node:fs/promises";import rC from"node:path";function B3($){return $}async function H3($){let f=rC.resolve($),J=await pC(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${W}`)}return iC(Q,f)}function iC($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var NG={};w(NG,{createLlmsSdk:()=>K3,DefaultLlmsSdk:()=>M6});import{BUILT_IN_PROVIDER_IDS as OG,createHandler as sC,createHandlerAsync as tC,getProviderCollection as oC,hasProvider as MG,registerAsyncHandler as eC,registerHandler as $E,registerModel as fE,registerProvider as TG}from"@cline/llms";function LG($){return $?{...$}:{}}function nC($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function aC($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function _G($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class A3{providers=new Map;register($){aC($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...LG($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:nC($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...LG($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class M6{configuredProviders=new A3;constructor($){this.applyConfig($)}createHandler($){return sC(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return tC(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(TG($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)$E($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)eC($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);TG({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){fE($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...OG]}async getBuiltInProviders(){return(await Promise.all(OG.map((f)=>oC(f)))).filter((f)=>f!==void 0).map((f)=>_G({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=MG(f.id),Q=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof Q==="string"&&MG(Q);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function K3($){return new M6($)}$W();async function JE(){return Promise.resolve().then(() => (F9(),yK))}function wE(){return new Date().toISOString()}var yE="cline",SE="cline-pass";function CE($){if(SG($)!=="providers.json")return;let f=F3($);if(SG(f)!=="settings")return;return F3(f)}class L1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??qE(),this.dataDir=$.dataDir??CE(this.filePath),this.dataDir||!$.filePath)O6({providerSettingsManager:this,dataDir:this.dataDir});if(fG(this),N9(this.read()),G3(this.filePath))try{yG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!G3(this.filePath))return U$();try{let $=TE(this.filePath,"utf8"),f=JSON.parse($),J=U2.safeParse(f);if(J.success)return N9(J.data),J.data}catch{}return U$()}write($){let f=U2.parse($),J=F3(this.filePath);if(!G3(J))ME(J,{recursive:!0,mode:448});NE(this.filePath,`${JSON.stringify(f,null,2)}
|
|
727
|
+
`,"utf8");try{yG(this.filePath,384)}catch{}N9(f)}saveProviderSettings($,f={}){let J=R2.parse($),Q=this.read(),Z=J.provider,W=f.setLastUsed!==!1,j=Q.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",Y={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:wE(),tokenSource:X}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,f){let J=$.providers[f]?.settings,Z=Q0(f)?.storageProviderId;if(!Z||Z===f)return J;let W=$.providers[Z]?.settings;if(!W)return J;return R2.parse({...W.auth?{auth:W.auth}:{},...W.apiKey?{apiKey:W.apiKey}:{},...W.baseUrl?{baseUrl:W.baseUrl}:{},...J??{},provider:f})}getProviderSettings($){let f=this.read();return this.resolveProviderSettings(f,$)}resolveLastUsedProviderId($,f){let J=$.lastUsedProvider;if(J===SE&&f.isClinePassEnabled===!1)return yE;return J}getLastUsedProviderSettings($={}){let f=this.read(),J=this.resolveLastUsedProviderId(f,$);if(!J)return;return this.resolveProviderSettings(f,J)}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return d0(J,f)}getLastUsedProviderConfig($={}){let f=this.getLastUsedProviderSettings($);if(!f)return;return d0(f,$)}async refreshCatalog(){try{await P2({})}catch{}}}L0();I2();function EE($,f){let J=$?.expiresAt,Q=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===Q}class u9 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class P3{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new L1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let f=Q0($.providerId);if(!f)return null;return this.resolveWithSingleFlight(f.providerId,f.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,f,J=!1){let Q=this.refreshInFlight.get(f);if(Q)return Q;let Z=this.resolveProviderApiKeyInternal($,f,J).catch((W)=>{throw W}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,Z),Z}async resolveProviderApiKeyInternal($,f,J){let Q=Q0($);if(!Q)return null;let Z=this.providerSettingsManager.getProviderSettings(f);if(!Z)return null;let W=R8($,Z);if(!W)return null;let j=await Q.refresh({settings:Z,credentials:W,forceRefresh:J,telemetry:this.telemetry});if(!j)throw new u9($);let X=I$({manager:this.providerSettingsManager,providerId:$,settings:Z,credentials:j,setLastUsed:!1,save:!1}),Y=!EE(Z.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Q.getApiKey(X)??j.access,accountId:j.accountId,refreshed:Y}}}import{normalizeUserInput as hE}from"@cline/shared";import{nanoid as bE}from"nanoid";class CG{list($){return $?e0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((Y)=>Y.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:e0($),updated:!1};let Z=$.pendingPrompts[Q];if(!Z)return{sessionId:f.sessionId,prompts:e0($),updated:!1};let W=f.prompt===void 0?Z.prompt:hE(f.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:W,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(Q,1),kE($,X,Q,Z.delivery),{sessionId:f.sessionId,prompts:e0($),prompt:d9(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:e0($),removed:!1};let[Z]=$.pendingPrompts.splice(Q,1);return{sessionId:f.sessionId,prompts:e0($),prompt:Z?d9(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=f,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===J);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:J,mode:Q??Y.mode,userImages:W??Y.userImages,userFiles:j??Y.userFiles};if(Z==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${bE(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return e0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(f<0)return{prompts:e0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:e0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:e0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),e0($)}clear($){return $.pendingPrompts.length=0,[]}}class D3{deps;service=new CG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:e0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,Q&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=d9(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function d9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function e0($){return $.pendingPrompts.map(d9)}function kE($,f,J,Q){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(Q==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class U3{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let Q=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=eQ(J),j=!!Q&&(!W.agentId||W.agentId===R3(Q.agent));$Z(Z,J,j?{isPrimaryAgentEvent:!0,agentId:R3(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(g7(J,f),f.type==="agent_event"){let Q={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};$Z(Q,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let Q=I1({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:R3(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(Q)e1(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await m7($,f,this.deps.invokeBackendOptional),J)v7(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!Y)return;let V=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let Q=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog($,f,J){let Q=this.deps.getSession($),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!f||typeof f!=="object")return;let W=f,j=typeof W.message==="string"?W.message:"";if(!j)return;let X=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(X.sessionId??=$,typeof W.pluginName==="string"&&W.pluginName)X.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,X);return}if(W.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function R3($){return $.getAgentId()}function z3($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:K$($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function L3($,f){let J=$[f];return typeof J==="function"?J:null}async function EG($,f,...J){let Q=L3($,f);if(!Q)throw Error(`session service method not available: ${f}`);return Promise.resolve(Q.apply($,J))}async function hG($,f,...J){let Q=L3($,f);if(!Q)return;await Promise.resolve(Q.apply($,J))}async function bG($,f,...J){let Q=L3($,f);if(!Q)return;return await Promise.resolve(Q.apply($,J))}H1();L0();function _3($,f,J){return{onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let Z=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let W=I1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(W)e1(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...W});V8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...W}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=$.getSession(J)?.runtime.teamRuntime,W=$.subAgentStarts.get(Q.subAgentId),j=W?Date.now()-W.startedAt:0,X=Q.result?.text?Q.result.text.split(`
|
|
728
|
+
`).length:0;V8(f.telemetry,{event:"ended",ulid:J,durationMs:j,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...I1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}}}function O3($,f,J,Q){let Z=_3($,f,J);return H$({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let j=f.enableTools?i$({cwd:f.cwd,...c0[b1({mode:f.mode})],executors:Q}):[];if(f.enableSpawnAgent)j.push(O3($,f,J,Q));return s$(j)},...Z})}import{readFile as IE,stat as xE}from"node:fs/promises";var gE=20480000;async function kG($){let f=await xE($);if(!f.isFile())throw Error("Path is not a file");if(f.size>gE)throw Error("File is too large to read into context.");let J=await IE($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var IG=5000;function T6($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function rE($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=T6(f.inputTokens),Q=T6(f.outputTokens),Z=T6(f.cacheReadTokens),W=T6(f.cacheWriteTokens),j=T6(f.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function iE($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class z1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new a4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new S$;constructor($){let f=vE();if(f)pE(f);let J=h0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new J8,this.createAgentInstance=$.createAgent??((Q)=>new Y$(Q)),this.defaultCapabilities=U0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new L1,this.oauthTokenManager=$.oauthTokenManager??new P3({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new D3({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new U3({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let f=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!f?.apiKey)return $;return{...$,config:{...$.config,apiKey:f.apiKey}}}async startSession($){let f=$.source??P0.CLI,J=e(),Q=$.config.sessionId?.trim()??"",Z=Q||uE(),W=await this.applyInitialOAuthCredentials($),j=W.initialMessages??[],X=j.length>0?W2(j):K0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=M3(Y,Z),B=M3(V,`${Z}.messages.json`),H=M3(V,`${Z}.json`),A=K$($.config),K=y0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:A,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:B}),G;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let S=await this.invokeOptionalValue("readSessionManifest",Z);if(S)K=S,G={manifestPath:H,messagesPath:S.messages_path||B,manifest:S}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??B,manifest:K});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,P);let F=U0(this.defaultCapabilities,$.capabilities),D=F?.toolExecutors??this.toolExecutors,_=$.localRuntime,O=_?.extensionContext?.logger??_?.logger,z=_?.extensionContext?.automation,U,N={getSession:(S)=>this.sessions.get(S),subAgentStarts:this.subAgentStarts,onAgentEvent:(S,G0,j0)=>this.eventBridge.dispatchAgentEvent(S,G0,j0),invokeBackendOptional:(S,...G0)=>this.invokeOptional(S,...G0)};U=await OV({input:W,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(S)=>{if(S.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,S.payload,O);return}this.eventBridge.handlePluginEvent(Z,S,z)},onTeamEvent:(S)=>{this.eventBridge.handleTeamEvent(Z,S),U.config.onTeamEvent?.(S)},createSpawnTool:()=>O3(N,U.config,Z,D),createSubAgentLifecycleCallbacks:(S)=>_3(N,S,Z),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(S)=>{await this.persistSessionMetadata(Z,()=>S)}});let y=await this.runtimeBuilder.build(U.runtimeBuilderInput),h=U.config,u=U.providerConfig;if(y.teamRuntime&&!h.teamName?.trim())h.teamName=y.teamRuntime.getTeamName();let t=[...y.tools,...h.extraTools??[]],f0=y.extensions??U.extensions,o={sessionId:Z,providerId:u.providerId,modelId:u.modelId,apiKey:u.apiKey,baseUrl:u.baseUrl,headers:u.headers,knownModels:u.knownModels,providerConfig:u,thinking:h.thinking,reasoningEffort:h.reasoningEffort??u.reasoningEffort,systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,execution:h.execution,prepareTurn:M8(h),tools:t,hooks:U.hooks,extensions:f0,hookErrorMode:h.hookErrorMode,initialMessages:U.effectiveInput.initialMessages,userFileContentLoader:kG,toolPolicies:U.toolPolicies,requestToolApproval:U.requestToolApproval?async(S)=>{let G0=U.requestToolApproval,j0=this.sessions.get(Z);if(j0)await this.markTurnPending(j0);try{if(!G0)return{approved:!1,reason:"Tool approval callback is not configured."};return await G0(S)}finally{let w0=this.sessions.get(Z);if(w0?.status==="pending")await this.markTurnRunning(w0)}}:void 0,telemetry:h.telemetry,onConsecutiveMistakeLimitReached:h.onConsecutiveMistakeLimitReached,completionPolicy:y.completionPolicy,consumePendingUserMessage:()=>{let S=this.pendingPromptsController.consumeSteer(Z);return S?Y6(S.prompt,S.mode??h.mode):void 0},logger:y.logger??h.logger,extensionContext:h.extensionContext,onEvent:(S)=>this.eventBridge.dispatchAgentEvent(Z,h,S)};o.hooks={...o.hooks,onEvent:async(S)=>{if(await U.hooks?.onEvent?.(S),S.type!=="assistant-message")return;let G0=this.sessions.get(Z);if(!G0)return;let j0=G0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,j0,h.systemPrompt)}catch(w0){h.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:w0}),hf(h.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:w0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:h.providerId,modelId:h.modelId}})}}};let $1=this.createAgentInstance(o);if(o.onEvent)$1.subscribeEvents(o.onEvent);y.registerLeadAgent?.($1);let E$=I1({agentId:$1.getAgentId(),conversationId:$1.getConversationId(),teamId:y.teamRuntime?.getTeamId(),teamName:y.teamRuntime?.getTeamName(),teamRole:y.teamRuntime?"lead":void 0});if(TV(h,Z,Q.length>0,A,E$),E$)e1(h.telemetry,{ulid:Z,modelId:h.modelId,provider:h.providerId,...E$});if(y.teamRuntime)u6(h.telemetry,{ulid:Z,teamId:y.teamRuntime.getTeamId(),teamName:y.teamRuntime.getTeamName(),leadAgentId:$1.getAgentId(),restoredFromPersistence:y.teamRestoredFromPersistence===!0});let n={sessionId:Z,config:h,sessionMetadata:W.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:y,agent:$1,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:U.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,n),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(n),await this.invoke("persistSessionMessages",n.sessionId,j,n.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(n,"completed",0)}let _1;try{if(W.prompt?.trim())if(_1=await this.executeTurn(n,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!n.interactive)await this.finalizeSingleRun(n,_1.finishReason);else await this.completeInteractiveTurn(n,_1.finishReason)}catch(S){if(n.interactive&&n.aborting)_1=await this.completeAbortedInteractiveTurn(n);else throw hf(n.config.telemetry,{component:"core",operation:"session.start",error:S,severity:"error",handled:!1,context:{sessionId:n.sessionId,providerId:n.config.providerId,modelId:n.config.modelId}}),await this.failSession(n),S}return{sessionId:Z,manifest:K,manifestPath:H,messagesPath:B,result:_1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let Q=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),Q=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw hf(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=A7(this.usageBySession.get($)),J=A7(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!W0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!W0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return z3(f);let J=$.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return s8(Q);let Z=await this.readManifest(J);return Z?I5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(s8),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(z3(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return M$(J.messagesPath);let Q=await this.readManifest(f);return M$(Q?.messages_path)}async dispatchHookEvent($){await rB($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,Q,J.userImages,J.userFiles);while(c7($,Z.finishReason)){let W=await u7($);if(W.length===0)break;let j=d7($,W);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(X6($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),Q=K0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,Q){let Z=$.started||$.agent.getMessages().length>0,W=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??K0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=K0(),$.turnUsageByAgent=new Map,k6($.config.telemetry,$.sessionId,$.config.mode),xf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=Z?()=>$.agent.continue(f,J,Q):()=>$.agent.run(f,J,Q),V=await this.runWithAuthRetry($,Y,W);$.started=!0;let B=_J(V.messages,V,W);$.persistedMessages=B;let H=o8($.turnUsageByAgent?.values()??[]),A=V0(j,V.usage),K=V0(V0(K0(),V.usage),H),G=V0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,B,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw hf($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((Q)=>Q.name===A0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,X8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=K$($.config),Q=lE(f.prompt).trim();if(!Q)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await af(Q,J);NV($.config.telemetry,Z);let W=Y6(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),Y=Array.from(new Set([...j,...X]));return{prompt:W,userImages:f.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=K$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(X6($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.shutdownSession($,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)X8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});e5($);let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),hf($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){Q("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),hf($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,W0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??e(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=Q.endedAt??e(),$.endedAt=W0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(Q){if(!k$($.config.providerId)||!dE(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(Q){if(Q instanceof u9)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new c1($);throw hf(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>cE(Q)?Q:T3($,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return I1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=V0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let Q=T3(f),Z=`${J}.messages.json`,W;try{W=mE($)}catch{return K0()}let j=K0();for(let X of W){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let Y=T3($,X);if(Y===Q)continue;let V=await M$(Y);if(V.length===0)continue;j=V0(j,W2(V))}return j}withPersistedAggregateUsageFloor($,f){let J=rE(f.metadata?.aggregateUsage);if(J)return iE($,J);let Q=f.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:F1({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),IG))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(IG)).find((Q)=>Q.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return EG(this.sessionService,$,...f)}invokeOptional($,...f){return hG(this.sessionService,$,...f)}invokeOptionalValue($,...f){return bG(this.sessionService,$,...f)}}function aE($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function sE($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function G9($={}){let f=new z1({sessionService:new U1(new D1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:nE(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:sE(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:aE(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}oE(process.env.CLINE_VCR);function $h($){let f=process.cwd(),J,Q,Z;for(let W=0;W<$.length;W+=1){let j=$[W],X=$[W+1];if(j==="--cwd"&&X){f=X,W+=1;continue}if(j==="--host"&&X){J=X,W+=1;continue}if(j==="--port"&&X){let Y=Number(X);if(Number.isFinite(Y))Q=Y;W+=1;continue}if(j==="--pathname"&&X)Z=X,W+=1}return{cwd:f,host:J,port:Q,pathname:Z}}async function fh(){let $=$h(process.argv.slice(2));process.chdir($.cwd);let f=i0({host:$.host,port:$.port,pathname:$.pathname}),J=await Sf({host:f.host,port:f.port,pathname:f.pathname,owner:eE()==="production"?n0():E0(),runtimeHandlers:G9(),cronOptions:{workspaceRoot:$.cwd}}),Q=async()=>{await J.close(),process.exit(0)},Z=!1,W=(j,X)=>{if(Z)return;Z=!0;let Y=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] ${j}: ${Y}
|
|
729
|
+
`),J.close().catch((V)=>{let B=V instanceof Error?V.stack||V.message:String(V);process.stderr.write(`[hub-daemon] shutdown after ${j} failed: ${B}
|
|
730
|
+
`)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{Q()}),process.on("SIGTERM",()=>{Q()}),process.on("uncaughtException",(j)=>{W("uncaughtException",j)}),process.on("unhandledRejection",(j)=>{if(j instanceof tE){process.stderr.write(`[hub-daemon] ignored agent runtime abort rejection: ${j.message}
|
|
731
|
+
`);return}W("unhandledRejection",j)}),await new Promise(()=>{})}fh().catch(($)=>{let f=$ instanceof Error?$.stack||$.message:String($);process.stderr.write(`[hub-daemon] fatal: ${f}
|
|
723
732
|
`),process.exit(1)});
|