@cline/core 0.0.62-nightly.1784171655 → 0.0.62

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.
@@ -201,7 +201,7 @@ Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for
201
201
  ${Q}`;return Z||Q}function Jq($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function jq($,W){return $.filter((Z)=>Jq(Z.name,W))}function Xq($,W){return n1(jq($,W))}function Yq($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:PH(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:PH(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class N${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 w3;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($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??ez,this.conversation=new q3($.initialMessages),this.messageBuilder=new O3(MH()),this.contributionRegistry=$q({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 Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new E3({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>Vq(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new N3(J)}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 W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=T2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){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($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await Zq(W);if(Z)$.push(Z)}return Qq(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}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 W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await Hq(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=UH(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=Xq([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=SH(this.config),H=Array.from(Y.values()),G=uW(this.conversation.getMessages()),K=NH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[MW]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=I8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}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 $=Yq([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=I8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:uW(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(dW($));return uW(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}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 W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?Wq(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>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 W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(I8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=I8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});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:Z,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 W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":Bq(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?I8(W.messages):this.conversation.getMessages(),H=SH(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function Vq($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function Bq($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function Hq($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => CH);return J($,W,Z,Q)}function SH($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=_3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as bH}from"@cline/shared";function yH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bH({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
202
202
  ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function hH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bH({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function E$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function z2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?yH($.prompt,W):hH($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function w$($){let W=z2($),Z=new N$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var Fq=C3.object({systemPrompt:C3.string().describe("System prompt defining the sub-agent's behavior"),task:C3.string().describe("Task for the sub-agent to complete")});function C$($){return Gq({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:Kq(Fq),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=w$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as D0,TEAM_AWAIT_TIMEOUT_MS as Aq,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as Uq,TEAM_RUN_TEXT_PREVIEW_LIMIT as Dq,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as _q,TeamAttachOutcomeFragmentInputSchema as kH,TeamAwaitRunsInputSchema as IH,TeamBroadcastInputSchema as xH,TeamBroadcastToolResultSchema as fq,TeamCancelRunInputSchema as gH,TeamCancelRunToolResultSchema as Lq,TeamCleanupInputSchema as mH,TeamCleanupToolResultSchema as Oq,TeamCreateOutcomeInputSchema as vH,TeamCreateOutcomeToolResultSchema as Tq,TeamFinalizeOutcomeInputSchema as cH,TeamFinalizeOutcomeToolResultSchema as zq,TeamListOutcomesInputSchema as uH,TeamListRunsInputSchema as dH,TeamMailboxMessageToolResultSchema as qq,TeamMissionLogInputSchema as lH,TeamMissionLogToolResultSchema as Mq,TeamOutcomeFragmentToolResultSchema as pH,TeamOutcomeToolResultSchema as Rq,TeamReadMailboxInputSchema as rH,TeamReviewOutcomeFragmentInputSchema as iH,TeamRunTaskInputSchema as nH,TeamRunTaskToolResultSchema as P3,TeamRunToolSummarySchema as S3,TeamSendMessageInputSchema as aH,TeamSendMessageToolResultSchema as Nq,TeamShutdownTeammateInputSchema as oH,TeamSimpleAgentStatusToolResultSchema as sH,TeamSpawnTeammateInputSchema as tH,TeamStatusInputSchema as eH,TeamStatusToolResultSchema as Eq,TeamTaskInputSchema as $G,TeamTaskToolResultSchema as d4,validateWithZod as g,zodToJsonSchema as _0}from"@cline/shared";function WG($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function q2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function wq($){let W=$.result;if(!W)return;return{textPreview:WG(W.text,Dq),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function iW($){return $?.toISOString()}function b3($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:WG($.message,Uq),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:iW($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:iW($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:iW($.heartbeatAt),lastProgressAt:iW($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:wq($)}}function Cq($){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 g8=["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 ZG($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...M2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:z2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function m8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=M2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;ZG({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function M2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(D0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:_0(tH),execute:async(X)=>{let Y=g(tH,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(ZG({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(M2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(sH,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(D0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:_0(oH),execute:async(X)=>{let Y=g(oH,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(sH,{agentId:Y.agentId,status:"stopped"})}})),J.push(D0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:_0(eH),execute:async(X)=>{return g(eH,X),g(Eq,$.runtime.getSnapshot())}})),J.push(D0({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:_0($G),execute:async(X)=>{let Y=g($G,X);switch(Y.action){case"create":{let V=new Set(_q.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:q2(Y.title,"title"),description:q2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(d4,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(d4,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(q2(Y.taskId,"taskId"),$.requesterId);return g(d4,{action:"claim",taskId:V.id,status:V.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 V=$.runtime.completeTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.summary,"summary"));return g(d4,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.reason,"reason"));return g(d4,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(D0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:_0(nH),execute:async(X)=>{let Y=g(nH,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(P3,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(P3,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(P3,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(D0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:_0(gH),execute:async(X)=>{let Y=g(gH,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(Lq,{runId:V.id,status:V.status})}})),J.push(D0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:_0(dH),execute:async(X)=>g(S3.array(),$.runtime.listRuns(g(dH,X)).map(b3))})),J.push(D0({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:_0(IH),timeoutMs:Aq,execute:async(X)=>{let Y=g(IH,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return Cq(H),g(S3,b3(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(S3.array(),V.map(b3))}})),J.push(D0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:_0(aH),execute:async(X)=>{let Y=g(aH,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(Nq,{id:V.id,toAgentId:V.toAgentId})}})),J.push(D0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:_0(xH),execute:async(X)=>{let Y=g(xH,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(fq,{delivered:V.length})}})),J.push(D0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:_0(rH),execute:async(X)=>{let Y=g(rH,X);return g(qq.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(D0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:_0(lH),execute:async(X)=>{let Y=g(lH,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(Mq,{id:V.id})}})),J.push(D0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:_0(mH),execute:async(X)=>{if(g(mH,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(Oq,{status:"cleaned"})}})),J.push(D0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:_0(vH),execute:async(X)=>{let Y=g(vH,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(Tq,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(D0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:_0(kH),execute:async(X)=>{let Y=g(kH,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(pH,{fragmentId:V.id,status:V.status})}})),J.push(D0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:_0(iH),execute:async(X)=>{let Y=g(iH,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(pH,{fragmentId:V.id,status:V.status})}})),J.push(D0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:_0(cH),execute:async(X)=>{let Y=g(cH,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(zq,{outcomeId:V.id,status:V.status})}})),J.push(D0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:_0(uH),execute:async(X)=>{return g(uH,X),g(Rq.array(),$.runtime.listOutcomes())}})),J}function nW($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function QG($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var Pq=[{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:C$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...g8]}],Sq={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function bq($){return $==="plan"||$==="yolo"?$:"act"}function jG($){let W=bq($.mode),Z=a0[i1({mode:W})],Q=k8($.providerId??"",$.modelId??"",W,h8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function JG($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=jG(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=Sq[$];return Q?Z[Q]===!0:!1}function yq($,W){if($.id==="editor"){let{flags:Z}=jG(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:JG($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:JG($.id,W)}}function R2($={}){return Pq.map((W)=>yq(W,$))}function aW($={}){return R2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function oW($){if(!$.enabled)return new Set;let W=R2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function l4($,W={}){return R2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function sW($,W={}){return l4($,W)}function N2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...y8(W),...Z??{}};return q$({...Q,executors:J})}import{mkdirSync as mq,writeFileSync as vq}from"node:fs";import{dirname as cq}from"node:path";import{normalizeUserInput as uq,stripModeNotices as dq}from"@cline/shared";import{nanoid as lq}from"nanoid";var YG={};w(YG,{sanitizeSessionToken:()=>E2,parseTeamTaskSubSessionId:()=>c8,parseSubSessionId:()=>r4,makeTeamTaskSubSessionId:()=>p4,makeSubSessionId:()=>v8,deriveSubsessionStatus:()=>i4});import{nanoid as Iq}from"nanoid";function E2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function v8($,W){let Z=E2($),Q=E2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function p4($,W){let Z=E2($),Q=E2(W);return`${Z}__teamtask__${Q}__${Iq(6)}`}function c8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function r4($){if(c8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function i4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var HG={};w(HG,{isTerminalSessionStatus:()=>BG,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>n4,NON_TERMINAL_SESSION_STATUSES:()=>VG});import{SESSION_STATUS_VALUES as xq}from"@cline/shared";var n4=xq,VG=["idle","running","pending"];function BG($){return!VG.includes($)}function K0($){return!BG($)}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 gq=Z0.enum(n4),x0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:gq,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function GG($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function h3($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function KG($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function a1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function y3($,W){let Z={...$};Z.id=a1(Z.id)??lq();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:a1(Q?.id)??a1(Z.modelId)??a1(W?.id),provider:a1(Q?.provider)??a1(Z.providerId)??a1(W?.provider),family:a1(Q?.family)??a1(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function tW($){return $.map((W)=>y3(W))}function eW($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return y3(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...y3(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function a4($){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 pq=120;function w2($){let W=$?.trim();return W?W.slice(0,pq):void 0}function k3($){let W=dq(uq($??"")).trim();if(!W)return;return w2(W.split(`
203
203
  `)[0]?.trim())}function P$($){if(!$)return;let W={...$},Z=w2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function o4($){let W=P$($.metadata)??{},Z=$.title!==void 0?w2($.title):k3($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function I3($){let W=c8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=r4($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function x3($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:tW($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function FG($,W,Z){mq(cq($),{recursive:!0}),vq($,`${JSON.stringify(x3({updatedAt:W,context:Z,messages:[]}),null,2)}
204
- `,"utf8")}function AG($,W){return x0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function UG($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}T0();var DG={};w(DG,{summarizeUsageFromMessages:()=>d8,sumUsageTotals:()=>s4,getCurrentContextSize:()=>g3,createInitialAccumulatedUsage:()=>q0,accumulateUsageTotals:()=>f0});function q0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function f0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function s4($){let W=q0();for(let Z of $)W=f0(W,Z);return W}function u8($){return typeof $==="number"&&Number.isFinite($)?$:0}function d8($){let W=q0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=f0(W,{inputTokens:u8(Q.inputTokens),outputTokens:u8(Q.outputTokens),cacheReadTokens:u8(Q.cacheReadTokens),cacheWriteTokens:u8(Q.cacheWriteTokens),totalCost:u8(Q.cost)})}return W}function g3($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=u8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function rq($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function m3($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function o1($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function iq($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function nq($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function v3($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=m3(W),G=o1({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=rq(W.input);if(K)e9(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(_8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))$W(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=iq(W);if(B){j.turnPrimaryUsage=f0(j.turnPrimaryUsage??q0(),K);let A=f0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),D8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),s9(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=nq({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,f0(D.get(A)??q0(),K))}let F=f0(j.turnPrimaryUsage??q0(),s4(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,f0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:KG(W),ts:Date.now()}})}function s1($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as JN}from"@cline/llms";import{hasRuntimeConfigExtension as jN}from"@cline/shared";var l8="0.0.62-nightly.1784171655";var t4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:l8,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"]};U1();import{existsSync as jZ,readFileSync as kM,statSync as IM}from"node:fs";import{basename as xM,dirname as QZ,join as XZ,resolve as JZ}from"node:path";import{discoverPluginModulePaths as gM,resolveConfiguredPluginModulePaths as gG,resolvePluginConfigSearchPaths as mM,SKILLS_CONFIG_DIRECTORY_NAME as vM}from"@cline/shared/storage";import{resolve as AM}from"node:path";import{normalizePluginManifest as UM}from"@cline/shared";import{existsSync as E0,readFileSync as r8}from"node:fs";import{builtinModules as aq,createRequire as l3}from"node:module";import{dirname as S$,extname as $5,isAbsolute as oq,resolve as o}from"node:path";import{fileURLToPath as LG}from"node:url";import{PLUGIN_FILE_EXTENSIONS as sq}from"@cline/shared";var OG=S$(LG(import.meta.url)),tq=l3(import.meta.url),eq=o(OG,"..","..","..","..",".."),c3=ZM(eq),$M=["@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"],p3=new Set(aq.flatMap(($)=>[$,$.replace(/^node:/,"")])),e4=new Set(sq),WM=["development","node","import","require","default"];function ZM($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(E0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!E0(j))continue;try{let X=JSON.parse(r8(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(E0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=QM(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function QM($,W){let Z=r3(W);if(!Z)return null;let Q=TG($,Z);for(let J of Q)if(E0(J))return J;return null}function r3($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of WM){let J=r3(Z[Q],W);if(J)return J}return null}function TG($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function JM($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function $Z($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function p8($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function jM($){let W=p8($);if($===W)return".";return`.${$.slice(W.length)}`}function zG($){return p8($).startsWith("@cline/")}function u3($,W){let Z=p8(W),Q=S$($);while(!0){let J=o(Q,"node_modules",Z);if(E0(J)||E0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function fG($){return d3($)!==null}function d3($){try{return tq.resolve($)}catch{}return XM($)}function XM($){let W=p8($),Z=qG(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(r8(Q,"utf8")),j=jM($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=r3(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...TG(Z,Y).filter((H)=>H!==V)];for(let H of B)if(E0(H))return H;return null}catch{return null}}function YM(){let $=[OG],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(S$(S$(W)));let Z=process.execPath?.trim();if(Z)$.push(S$(Z));return[...new Set($.map((Q)=>o(Q)))]}function VM($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(E0(Q))try{if(JSON.parse(r8(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(E0(J))return S$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function qG($){for(let W of YM()){let Z=VM(W,$);if(Z)return Z}return null}function BM($){let Z=S$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(E0(J))try{let X=JSON.parse(r8(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function MG($,W){let Z=W.startsWith("file:")?LG(W):oq(W)?W:o(S$($),W);if(E0(Z)&&e4.has($5(Z)))return Z;for(let Q of e4){let J=`${Z}${Q}`;if(E0(J))return J}for(let Q of e4){let J=o(Z,`index${Q}`);if(E0(J))return J}return null}function RG($){let W=new Set,Z=[/\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 Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function HM($){return $5($)!==".ts"}function NG($,W,Z=new Set){if(Z.has($)||!E0($))return;if(Z.add($),!e4.has($5($)))return;let Q=r8($,"utf8"),J=HM($);for(let j of RG(Q)){if(j.startsWith("node:")||p3.has(j))continue;if($Z(j)){if(!J)continue;if(Object.hasOwn(c3,j)||Object.hasOwn(c3,p8(j))||u3($,j)||zG(j)&&fG(j)||W&&fG(j))continue;throw Error(`Cannot find module '${p8(j)}'`)}let X=MG($,j);if(X)NG(X,W,Z)}}function EG($,W=new Set,Z=new Set){if(W.has($)||!E0($))return Z;if(W.add($),!e4.has($5($)))return Z;let Q=r8($,"utf8");for(let J of RG(Q)){if(Z.add(J),$Z(J))continue;let j=MG($,J);if(j)EG(j,W,Z)}return Z}function GM($,W){let Z=l3($),Q={},J=EG($),j=new Set($M);for(let[X,Y]of Object.entries(c3)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if($Z(X)&&(zG(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||u3($,X))continue;let Y=d3(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!$Z(X)||Object.hasOwn(Q,X)||u3($,X)||X.startsWith("node:")||p3.has(X))continue;let Y=d3(X);if(Y)Q[X]=Y}return Q}function KM($){let W=$5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var C2;function FM(){if(C2!==void 0)return C2;let $=qG("jiti");if(!$)return C2=null,null;let W=o($,"dist","babel.cjs");if(!E0(W))return C2=null,null;try{let Q=l3(W)(W);C2=typeof Q==="function"?Q:null}catch{C2=null}return C2}async function wG($,W={}){let Z=!BM($);NG($,Z);let Q=GM($,Z),J=JM(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>KM(G)).map(([G])=>G),V=FM(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...p3],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function CG($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function PG($){return typeof $==="object"&&$!==null}function i3($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function DM($,W){if(!PG($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!i3($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!i3($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!i3($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function _M($,W){if(!PG($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);DM($,W)}async function W5($,W={}){let Z=AM(W.cwd??process.cwd(),$),Q=await wG(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];_M(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:UM(X.manifest),setup:V}}async function WZ($,W={}){return(await P2($,W)).plugins}async function P2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await W5(Y,W);if(!CG(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as s3}from"node:fs";import{createRequire as xG}from"node:module";import{dirname as ZZ,join as n8}from"node:path";import{fileURLToPath as zM}from"node:url";var kG={};w(kG,{resolveSubprocessRuntimeExecutable:()=>n3,buildSubprocessSandboxCommand:()=>hG,SubprocessSandbox:()=>i8,CLINE_JS_RUNTIME_PATH_ENV:()=>yG});import{spawn as fM}from"node:child_process";import{basename as LM}from"node:path";import{augmentNodeCommandForDebug as OM,withResolvedClineBuildEnv as TM}from"@cline/shared";function SG($){if($ instanceof Error)return $;return Error(String($))}var yG="CLINE_JS_RUNTIME_PATH";function bG($){let W=$?.trim();if(!W)return!1;let Z=LM(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function n3($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[yG]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(bG(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&bG(j))return j}return"node"}function hG($,W={}){let Z=n3({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return OM([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class i8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=hG($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=fM(W[0]??n3(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:TM(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${SG(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${SG(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),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 W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function qM($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Z5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function MM(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function RM(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=xG($).resolve(`${MM()}/package.json`),Q=n8(ZZ(Z),"extensions","plugin-sandbox-bootstrap.js");return s3(Q)?Q:void 0}catch{return}}function NM(){let $=process.execPath?.trim();if(!$)return;let W=n8(ZZ(ZZ($)),"extensions","plugin-sandbox-bootstrap.js");return s3(W)?W:void 0}function EM(){let $=ZZ(zM(import.meta.url)),W=xG(import.meta.url),Z=[n8($,"plugin-sandbox-bootstrap.js"),n8($,"extensions","plugin-sandbox-bootstrap.js"),n8($,"agents","plugin-sandbox-bootstrap.js"),RM(),NM()];for(let j of Z.filter((X)=>typeof X==="string"))if(s3(j))return{file:j};let Q=n8($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`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(`
204
+ `,"utf8")}function AG($,W){return x0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function UG($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}T0();var DG={};w(DG,{summarizeUsageFromMessages:()=>d8,sumUsageTotals:()=>s4,getCurrentContextSize:()=>g3,createInitialAccumulatedUsage:()=>q0,accumulateUsageTotals:()=>f0});function q0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function f0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function s4($){let W=q0();for(let Z of $)W=f0(W,Z);return W}function u8($){return typeof $==="number"&&Number.isFinite($)?$:0}function d8($){let W=q0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=f0(W,{inputTokens:u8(Q.inputTokens),outputTokens:u8(Q.outputTokens),cacheReadTokens:u8(Q.cacheReadTokens),cacheWriteTokens:u8(Q.cacheWriteTokens),totalCost:u8(Q.cost)})}return W}function g3($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=u8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function rq($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function m3($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function o1($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function iq($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function nq($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function v3($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=m3(W),G=o1({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=rq(W.input);if(K)e9(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(_8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))$W(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=iq(W);if(B){j.turnPrimaryUsage=f0(j.turnPrimaryUsage??q0(),K);let A=f0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),D8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),s9(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=nq({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,f0(D.get(A)??q0(),K))}let F=f0(j.turnPrimaryUsage??q0(),s4(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,f0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:KG(W),ts:Date.now()}})}function s1($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as JN}from"@cline/llms";import{hasRuntimeConfigExtension as jN}from"@cline/shared";var l8="0.0.62";var t4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:l8,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"]};U1();import{existsSync as jZ,readFileSync as kM,statSync as IM}from"node:fs";import{basename as xM,dirname as QZ,join as XZ,resolve as JZ}from"node:path";import{discoverPluginModulePaths as gM,resolveConfiguredPluginModulePaths as gG,resolvePluginConfigSearchPaths as mM,SKILLS_CONFIG_DIRECTORY_NAME as vM}from"@cline/shared/storage";import{resolve as AM}from"node:path";import{normalizePluginManifest as UM}from"@cline/shared";import{existsSync as E0,readFileSync as r8}from"node:fs";import{builtinModules as aq,createRequire as l3}from"node:module";import{dirname as S$,extname as $5,isAbsolute as oq,resolve as o}from"node:path";import{fileURLToPath as LG}from"node:url";import{PLUGIN_FILE_EXTENSIONS as sq}from"@cline/shared";var OG=S$(LG(import.meta.url)),tq=l3(import.meta.url),eq=o(OG,"..","..","..","..",".."),c3=ZM(eq),$M=["@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"],p3=new Set(aq.flatMap(($)=>[$,$.replace(/^node:/,"")])),e4=new Set(sq),WM=["development","node","import","require","default"];function ZM($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(E0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!E0(j))continue;try{let X=JSON.parse(r8(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(E0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=QM(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function QM($,W){let Z=r3(W);if(!Z)return null;let Q=TG($,Z);for(let J of Q)if(E0(J))return J;return null}function r3($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of WM){let J=r3(Z[Q],W);if(J)return J}return null}function TG($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function JM($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function $Z($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function p8($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function jM($){let W=p8($);if($===W)return".";return`.${$.slice(W.length)}`}function zG($){return p8($).startsWith("@cline/")}function u3($,W){let Z=p8(W),Q=S$($);while(!0){let J=o(Q,"node_modules",Z);if(E0(J)||E0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function fG($){return d3($)!==null}function d3($){try{return tq.resolve($)}catch{}return XM($)}function XM($){let W=p8($),Z=qG(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(r8(Q,"utf8")),j=jM($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=r3(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...TG(Z,Y).filter((H)=>H!==V)];for(let H of B)if(E0(H))return H;return null}catch{return null}}function YM(){let $=[OG],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(S$(S$(W)));let Z=process.execPath?.trim();if(Z)$.push(S$(Z));return[...new Set($.map((Q)=>o(Q)))]}function VM($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(E0(Q))try{if(JSON.parse(r8(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(E0(J))return S$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function qG($){for(let W of YM()){let Z=VM(W,$);if(Z)return Z}return null}function BM($){let Z=S$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(E0(J))try{let X=JSON.parse(r8(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function MG($,W){let Z=W.startsWith("file:")?LG(W):oq(W)?W:o(S$($),W);if(E0(Z)&&e4.has($5(Z)))return Z;for(let Q of e4){let J=`${Z}${Q}`;if(E0(J))return J}for(let Q of e4){let J=o(Z,`index${Q}`);if(E0(J))return J}return null}function RG($){let W=new Set,Z=[/\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 Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function HM($){return $5($)!==".ts"}function NG($,W,Z=new Set){if(Z.has($)||!E0($))return;if(Z.add($),!e4.has($5($)))return;let Q=r8($,"utf8"),J=HM($);for(let j of RG(Q)){if(j.startsWith("node:")||p3.has(j))continue;if($Z(j)){if(!J)continue;if(Object.hasOwn(c3,j)||Object.hasOwn(c3,p8(j))||u3($,j)||zG(j)&&fG(j)||W&&fG(j))continue;throw Error(`Cannot find module '${p8(j)}'`)}let X=MG($,j);if(X)NG(X,W,Z)}}function EG($,W=new Set,Z=new Set){if(W.has($)||!E0($))return Z;if(W.add($),!e4.has($5($)))return Z;let Q=r8($,"utf8");for(let J of RG(Q)){if(Z.add(J),$Z(J))continue;let j=MG($,J);if(j)EG(j,W,Z)}return Z}function GM($,W){let Z=l3($),Q={},J=EG($),j=new Set($M);for(let[X,Y]of Object.entries(c3)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if($Z(X)&&(zG(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||u3($,X))continue;let Y=d3(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!$Z(X)||Object.hasOwn(Q,X)||u3($,X)||X.startsWith("node:")||p3.has(X))continue;let Y=d3(X);if(Y)Q[X]=Y}return Q}function KM($){let W=$5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var C2;function FM(){if(C2!==void 0)return C2;let $=qG("jiti");if(!$)return C2=null,null;let W=o($,"dist","babel.cjs");if(!E0(W))return C2=null,null;try{let Q=l3(W)(W);C2=typeof Q==="function"?Q:null}catch{C2=null}return C2}async function wG($,W={}){let Z=!BM($);NG($,Z);let Q=GM($,Z),J=JM(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>KM(G)).map(([G])=>G),V=FM(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...p3],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function CG($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function PG($){return typeof $==="object"&&$!==null}function i3($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function DM($,W){if(!PG($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!i3($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!i3($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!i3($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function _M($,W){if(!PG($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);DM($,W)}async function W5($,W={}){let Z=AM(W.cwd??process.cwd(),$),Q=await wG(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];_M(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:UM(X.manifest),setup:V}}async function WZ($,W={}){return(await P2($,W)).plugins}async function P2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await W5(Y,W);if(!CG(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as s3}from"node:fs";import{createRequire as xG}from"node:module";import{dirname as ZZ,join as n8}from"node:path";import{fileURLToPath as zM}from"node:url";var kG={};w(kG,{resolveSubprocessRuntimeExecutable:()=>n3,buildSubprocessSandboxCommand:()=>hG,SubprocessSandbox:()=>i8,CLINE_JS_RUNTIME_PATH_ENV:()=>yG});import{spawn as fM}from"node:child_process";import{basename as LM}from"node:path";import{augmentNodeCommandForDebug as OM,withResolvedClineBuildEnv as TM}from"@cline/shared";function SG($){if($ instanceof Error)return $;return Error(String($))}var yG="CLINE_JS_RUNTIME_PATH";function bG($){let W=$?.trim();if(!W)return!1;let Z=LM(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function n3($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[yG]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(bG(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&bG(j))return j}return"node"}function hG($,W={}){let Z=n3({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return OM([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class i8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=hG($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=fM(W[0]??n3(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:TM(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${SG(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${SG(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),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 W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function qM($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Z5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function MM(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function RM(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=xG($).resolve(`${MM()}/package.json`),Q=n8(ZZ(Z),"extensions","plugin-sandbox-bootstrap.js");return s3(Q)?Q:void 0}catch{return}}function NM(){let $=process.execPath?.trim();if(!$)return;let W=n8(ZZ(ZZ($)),"extensions","plugin-sandbox-bootstrap.js");return s3(W)?W:void 0}function EM(){let $=ZZ(zM(import.meta.url)),W=xG(import.meta.url),Z=[n8($,"plugin-sandbox-bootstrap.js"),n8($,"extensions","plugin-sandbox-bootstrap.js"),n8($,"agents","plugin-sandbox-bootstrap.js"),RM(),NM()];for(let j of Z.filter((X)=>typeof X==="string"))if(s3(j))return{file:j};let Q=n8($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`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(`
205
205
  `)}}var a3=EM();function o3($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function a8($){let W=new i8({name:"plugin-sandbox",..."file"in a3?{bootstrapFile:a3.file}:{bootstrapScript:a3.script},onEvent:$.onEvent}),Z=o3($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=o3($.hookTimeoutMs,3000),J=o3($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(qM);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{wM(F,W,G,J,Y),CM(F,W,G,J,Y),PM(F,W,G,J,Y),bM(F,W,G,J,Y),SM(F,G)}};return K.hooks=hM(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function wM($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!Z5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function CM($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!Z5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function PM($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!Z5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function SM($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function bM($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return IG(Y)?Y:X}catch(Y){if(!Z5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return IG(V)?V:X}}})}function IG($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function yM($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!Z5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function hM($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=yM($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var e3="package.json",cM="package";function Q5($){return mM($)}function J5($){return gM($)}function uM($){try{return jZ($)&&IM($).isDirectory()}catch{return!1}}function $J($){let W=[],Z=new Set;for(let Q of $){let J=JZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function mG($){let W=$J($);return vW(W)}function vG($){return Q5($).flatMap((W)=>J5(W)).filter((W)=>jZ(W))}function dM($,W){let Z=[];for(let Q of $)try{Z.push(...gG([Q],W))}catch{}return Z}function t3($){return typeof $==="object"&&$!==null}function lM($){try{let W=JSON.parse(kM(XZ($,e3),"utf8"));if(!t3(W)||!t3(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!t3(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function cG($,W){let Z=JZ(W);return lM($).some((Q)=>JZ($,Q)===Z)}function pM($,W){return xM($)===cM&&jZ(XZ(QZ($),e3))&&cG(QZ($),W)}function rM($){let W=JZ($),Z=[],Q=QZ(W);while(!0){if(pM(Q,W)){Z.push(Q);break}if(jZ(XZ(Q,e3))){if(cG(Q,W))Z.push(Q);break}let J=QZ(Q);if(J===Q)break;Q=J}return $J(Z)}function t1($={}){let W=$.cwd??process.cwd(),Z=vG($.workspacePath),Q=gG($.pluginPaths??[],W);return mG([...Q,...Z])}function iM($={}){let W=$.cwd??process.cwd(),Z=vG($.workspacePath),Q=dM($.pluginPaths??[],W);return mG([...Q,...Z])}function e1($){let W=[];for(let Z of $)for(let Q of rM(Z)){let J=XZ(Q,vM);if(uM(J))W.push(J)}return $J(W)}function uG($={}){return e1(iM($))}async function o8($={}){let W=t1($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await P2(W,{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 Z=await a8({pluginPaths:W,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:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as nM}from"node:child_process";import{promisify as aM}from"node:util";var oM=aM(nM);function WJ($,W){$?.log(W,{severity:"warn"})}function sM($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function S2($,W){let Z=await oM("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function ZJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await S2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
206
206
  `).filter(Boolean);await Promise.allSettled(J.map((j)=>S2($,["update-ref","-d",j])))}catch{}}async function dG($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>S2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function tM($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function lG($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await S2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await S2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){WJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await S2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return WJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await S2($.cwd,["update-ref",V,Y])}catch(B){WJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=sM(Y);if(V?.latest.ref===X.ref)return;let B=tM(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as YR}from"node:child_process";import{appendFileSync as VR,readFileSync as BR}from"node:fs";import{join as HR}from"node:path";import{augmentNodeCommandForDebug as iG,withResolvedClineBuildEnv as jJ}from"@cline/shared";import{ensureHookLogDir as pG}from"@cline/shared/storage";function s8($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as eM,readdirSync as $R}from"node:fs";import{basename as WR,extname as ZR,join as QR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as YZ,resolveHooksConfigSearchPaths as JR}from"@cline/shared/storage";function j5($){return JR($)}var t8;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(t8||={});var X5={["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"},jR=new Map(Object.values(t8).map(($)=>[$.toLowerCase(),$])),XR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function Y5($){let W=ZR($).toLowerCase();if(!XR.has(W))return;let Z=WR($,W).trim().toLowerCase();return jR.get(Z)}function b$($){let W=[],Z=new Set,Q=j5($).filter((J)=>eM(J));for(let J of Q)try{for(let j of $R(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=Y5(j.name);if(!X)continue;let Y=QR(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:X5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function BZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function VZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function GR($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
207
207
  `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function KR($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function QJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function w0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function FR($){let W=$.trim();if(!W)return{};let Q=W.split(`
package/dist/hub/index.js CHANGED
@@ -273,7 +273,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
273
273
  error = ?,
274
274
  scheduled_for = COALESCE(?, scheduled_for),
275
275
  updated_at = ?
276
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}}function a9($){return $?new Date($).getTime():void 0}function LL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function n9($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:a9($.nextRunAt),lastRunAt:a9($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:LL($)}}function TL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function u7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a9($.startedAt),endedAt:a9($.completedAt),status:TL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath}),this.materializer=new e6({store:this.store}),this.runner=new Z4({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(g7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n9(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?n9(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>n9(W))}updateSchedule($,W){if(W.cronPattern!==void 0)g7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?n9(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return u7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),u7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return u7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}fW();import{createSessionId as HO,isHubProtocolCompatible as GO,resolveClineBuildEnv as KO,resolveHubCommandTimeoutMs as FO}from"@cline/shared";var vV={};w(vV,{splitCoreSessionConfig:()=>D4,isSessionNotFoundError:()=>p1,SessionNotFoundError:()=>l1,SESSION_NOT_FOUND_ERROR_CODE:()=>X2});var X2="session_not_found";class l1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function p1($){return $ instanceof l1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function D4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as cT}from"node:child_process";import{closeSync as uT,mkdirSync as dT,openSync as lT}from"node:fs";import{basename as pT,dirname as rT,join as iT}from"node:path";import{fileURLToPath as nT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aT,isHubDaemonProcess as eV,isHubProtocolCompatible as oT,resolveClineBuildEnv as $B,withResolvedClineBuildEnv as sT}from"@cline/shared";import{createHash as _T,randomBytes as fT}from"node:crypto";import{existsSync as LT}from"node:fs";import{chmod as TT,mkdir as n7,readFile as lV,rm as a7,writeFile as pV}from"node:fs/promises";import{dirname as rV,join as o7}from"node:path";import{resolveClineDataDir as Y2,resolveClineDir as iV}from"@cline/shared/storage";var R8="0.0.62-nightly.1784171655";var _4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:R8,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 OT="CLINE_HUB_DISCOVERY_PATH",zT="CLINE_HUB_BUILD_ID",uV=30000,qT=15000,MT=100;function RT($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ET($){return _T("sha256").update($).digest("hex").slice(0,12)}function NT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function LW(){return fT(32).toString("hex")}function wT($){return new Promise((W)=>setTimeout(W,$))}function CT($){return`${$}.lock`}async function PT($){try{let W=JSON.parse(await lV(o7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function dV($){await a7($,{recursive:!0,force:!0}).catch(()=>{return})}function TW(){return process.env[zT]?.trim()||String(_4.version)}function r1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${ET($)}`,Z=process.env[OT]?.trim()||o7(Y2(),"locks","hub","owners",`${RT(W)}.json`);return{ownerId:W,discoveryPath:Z}}function nV($=`hub-${Date.now().toString(36)}`){return r1($)}async function D0($){try{let W=JSON.parse(await lV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function OW($,W){await n7(rV($),{recursive:!0}),await a7($,{force:!0}).catch(()=>{return}),await pV($,`${JSON.stringify(W,null,2)}
276
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}}function a9($){return $?new Date($).getTime():void 0}function LL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function n9($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:a9($.nextRunAt),lastRunAt:a9($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:LL($)}}function TL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function u7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a9($.startedAt),endedAt:a9($.completedAt),status:TL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath}),this.materializer=new e6({store:this.store}),this.runner=new Z4({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(g7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n9(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?n9(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>n9(W))}updateSchedule($,W){if(W.cronPattern!==void 0)g7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?n9(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return u7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),u7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return u7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}fW();import{createSessionId as HO,isHubProtocolCompatible as GO,resolveClineBuildEnv as KO,resolveHubCommandTimeoutMs as FO}from"@cline/shared";var vV={};w(vV,{splitCoreSessionConfig:()=>D4,isSessionNotFoundError:()=>p1,SessionNotFoundError:()=>l1,SESSION_NOT_FOUND_ERROR_CODE:()=>X2});var X2="session_not_found";class l1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function p1($){return $ instanceof l1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function D4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as cT}from"node:child_process";import{closeSync as uT,mkdirSync as dT,openSync as lT}from"node:fs";import{basename as pT,dirname as rT,join as iT}from"node:path";import{fileURLToPath as nT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aT,isHubDaemonProcess as eV,isHubProtocolCompatible as oT,resolveClineBuildEnv as $B,withResolvedClineBuildEnv as sT}from"@cline/shared";import{createHash as _T,randomBytes as fT}from"node:crypto";import{existsSync as LT}from"node:fs";import{chmod as TT,mkdir as n7,readFile as lV,rm as a7,writeFile as pV}from"node:fs/promises";import{dirname as rV,join as o7}from"node:path";import{resolveClineDataDir as Y2,resolveClineDir as iV}from"@cline/shared/storage";var R8="0.0.62";var _4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:R8,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 OT="CLINE_HUB_DISCOVERY_PATH",zT="CLINE_HUB_BUILD_ID",uV=30000,qT=15000,MT=100;function RT($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ET($){return _T("sha256").update($).digest("hex").slice(0,12)}function NT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function LW(){return fT(32).toString("hex")}function wT($){return new Promise((W)=>setTimeout(W,$))}function CT($){return`${$}.lock`}async function PT($){try{let W=JSON.parse(await lV(o7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function dV($){await a7($,{recursive:!0,force:!0}).catch(()=>{return})}function TW(){return process.env[zT]?.trim()||String(_4.version)}function r1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${ET($)}`,Z=process.env[OT]?.trim()||o7(Y2(),"locks","hub","owners",`${RT(W)}.json`);return{ownerId:W,discoveryPath:Z}}function nV($=`hub-${Date.now().toString(36)}`){return r1($)}async function D0($){try{let W=JSON.parse(await lV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function OW($,W){await n7(rV($),{recursive:!0}),await a7($,{force:!0}).catch(()=>{return}),await pV($,`${JSON.stringify(W,null,2)}
277
277
  `,{encoding:"utf8",mode:384}),await TT($,384)}async function g0($){await a7($,{force:!0}).catch(()=>{return})}async function zW($,W){let Z=CT($);await n7(rV(Z),{recursive:!0});let Q=Date.now()+qT;while(!0)try{await n7(Z,{recursive:!1}),await pV(o7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
278
  `,"utf8");try{return await W()}finally{await dV(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await PT(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):uV+1;if(!X||!NT(X.pid)||Y>uV){await dV(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await wT(MT)}}async function i1($,W){try{let Z=await fetch(W?.authToken?s7($):qW($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.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((J)=>typeof J==="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 Y1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function qW($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function s7($){let W=new URL(qW($));return W.pathname="/status",W.toString()}function aV($){return LT($)}import{CLINE_HUB_DEV_PORT as ST,CLINE_HUB_PORT as bT,resolveClineBuildEnv as yT}from"@cline/shared";var hT="CLINE_HUB_HOST",kT="CLINE_HUB_PORT",IT="CLINE_HUB_PATHNAME",t7="127.0.0.1",e7=bT,$3="/hub";function oV($){return yT($)==="development"?ST:e7}function W3($={}){return($.env??process.env)[hT]?.trim()||t7}function E8($={}){let Z=($.env??process.env)[kT]?.trim();if(!Z)return oV($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return oV($);return Q}function Z3($={}){return($.env??process.env)[IT]?.trim()||$3}function T1($={},W={}){return{host:$.host??W3(W),port:$.port??E8(W),pathname:$.pathname??Z3(W)}}import{join as xT}from"node:path";var gT="shared:cline",mT="CLINE_HUB_DISCOVERY_PATH",vT="hub-production";function sV($){let W=_1($.trim());return r1(`workspace:${W||$.trim()}`)}function V1($=gT){return r1($)}function O1(){return{ownerId:vT,discoveryPath:process.env[mT]?.trim()||xT(Y2(),"locks","hub","production.json")}}var tT=8000,eT=200,$O=3000,WO=100,ZO=[100,250,500,1000,2000],QO="--cline-hub-daemon";function JO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function jO(){try{let $=iT(Y2(),"logs","hub-daemon.log");return dT(rT($),{recursive:!0}),{fd:lT($,"a"),logPath:$}}catch{return}}function WB(){return $B()==="production"?O1():V1()}function V2($){return oT($).compatible}function tV($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function B2($,W){try{return await i1($,{authToken:W})}catch{return}}async function XO($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await B2($))?.url)return!0;await new Promise((J)=>setTimeout(J,WO))}return!1}async function MW($,W){if(await L4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await XO($.url,$O);return await g0(W).catch(()=>{return}),Z}async function f4($,W){if(V2($))return!0;return MW($,W)}async function ZB($){if($B()!=="production")return;let W=V1();if(W.discoveryPath===$.discoveryPath)return;let Z=await D0(W.discoveryPath);if(Z?.url)await MW(Z,W.discoveryPath);else await g0(W.discoveryPath).catch(()=>{return})}function YO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return nT(new URL(`./entry.${$}`,import.meta.url))}function VO($,W){let Z=YO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=pT(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[QO]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...JO(W)],cwd:$,env:{...sT(process.env),CLINE_NO_INTERACTIVE:"1",[aT]:"1"}}}function BO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function Q3($,W={}){if(eV())return;let Z=VO($,W),Q=jO();try{cT(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)uT(Q.fd)}}async function N8($,W={}){for(let Z=0;;Z++)try{Q3($,W);return}catch(Q){let J=ZO[Z];if(!BO(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function RW($,W={}){if(eV())return;let Z=WB(),Q=T1(W),J=Y1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;ZB(Z).catch(()=>{return}).then(()=>D0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await MW(X,Z.discoveryPath)&&!j)return}else{let H=await B2(X.url,X.authToken);if(H?.url&&V2(H)&&await z1(H.url,{authToken:X.authToken}))return;if(H?.url)await f4({...H,authToken:X.authToken},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}let V=await B2(J);if(V?.url){if(V2(V)){if(!j||!Y)return}else if(!await f4({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await N8($,B)}).catch(()=>{})}async function QB($,W={}){let Z=WB(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=T1(W),j=Y1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)O$(F.url,F.authToken);return F};await ZB(Z).catch(()=>{return});let Y=await D0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await MW(Y,Z.discoveryPath);else{let A=await B2(Y.url,F);if(A?.url&&V2(A)&&await z1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await f4({...A,authToken:F},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}}let B=await B2(j);if(B?.url){let F=tV(B,Y,j);if(V2(B))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" 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 f4(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await N8($,G);let K=Date.now()+tT;while(Date.now()<K){let F=await D0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await B2(F.url,F.authToken);if(D?.url&&V2(D)&&await z1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await B2(j);if(A?.url&&!V2(A)){let D=tV(A,F,j);if(!await f4(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((D)=>setTimeout(D,eT))}throw Error("Timed out waiting for detached hub startup.")}function EW(){return KO()==="production"?O1():V1()}function AO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function VB($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return VB($.data);return String($)}function UO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function JB($){let W=$,Z=UO(W.reason);return new y0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:J3,{closeCode:W.code,closeReason:Z||void 0})}function DO($,W){if($ instanceof y0)return $;if($ instanceof Error)return new y0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new y0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new y0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new y0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var _O=8000,fO=200,jB="*",XB=8000,LO="cline-hub-auth.",BB=new Map,HB=new Set,TO=3000,OO=3000,zO=100,J3="Hub connection closed",qO=250,MO=5000,YB=0.5;class y0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function Y3($){return $ instanceof y0}class w8 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function NW($,W){return $ instanceof w8&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function GB($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=V3($.toString());return Z?BB.get(Z):void 0}function RO($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function V3($){if(!RO($))return;let W=new URL(z$($));return W.search="",W.hash="",W.toString()}function j3($){let W=V3($);return!!W&&HB.has(W)}function O$($,W){let Z=V3($);if(Z){if(HB.add(Z),W?.trim())BB.set(Z,W)}return $}class B1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new y0("hub_connection_closed",J3);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),W=this.options.authToken?.trim()||GB($);$.hash="";let Q=new(AO())($.toString(),W?[`${LO}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new y0("hub_connect_timeout",`Timed out connecting to hub after ${XB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},XB);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=DO(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=JB(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(VB(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=JB(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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 j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=HO("hubreq_"),j=FO($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new w8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===X2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new l1(V,Y.error.message)}throw new w8($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!j3(this.currentUrl)||!Y3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(qO*2**this.reconnectAttempt,MO),W=Math.round($*(1-YB)+Math.random()*$*YB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!j3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await H2({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 y0("hub_connection_closed",J3),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 y0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??jB}subscriptionSessionIdFromKey($){return $===jB?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function z$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function z1($,W){let Z=new B1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function X3($,W){let Z=z$($),Q=await i1(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!GO(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await z1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function EO($){let W=Date.now()+_O;while(Date.now()<W){let Z=await D0($.discoveryPath);if(Z?.url){let Q=await X3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,fO))}return}async function NO($){let W=Date.now()+OO;while(Date.now()<W){if(!(await i1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,zO))}return!1}function wO($,W){try{return z$($)===z$(W)}catch{return!1}}function CO($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function PO($,W,Z){let Q=new B1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:TO});return!CO(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function T4($={}){if($.endpoint?.trim()){let J=await X3($.endpoint);return J.status==="compatible"?J.url:void 0}let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url)return;let Q=await X3(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await g0(W.discoveryPath).catch(()=>{return});return}async function H2($={}){let W=await T4($);if(W&&await z1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=EW();return await N8($.workspaceRoot??process.cwd()),await EO(Z)}async function L4($,W){let Z=new URL($),Q=W?.trim()||GB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function B3($=EW()){let W=await D0($.discoveryPath);if(!W?.url)return!1;try{if(await L4(W.url,W.authToken))return!0}catch{}return!1}async function wW($){if(!j3($.url))return;let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url||!wO(Z.url,$.url))return;if(!await PO(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await B3())return;if(!await NO(Z.url))return;return await g0(W.discoveryPath).catch(()=>{return}),await H2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as SO}from"@cline/shared";function bO($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var yO="cline-hub-auth.";function hO($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function kO($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function KB(){return SO()==="production"?O1():V1()}async function IO($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url&&kO($.toString(),Q.url))return Q.authToken;return}async function H3($={}){let W=T1($);if(!hO($)){let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url)return Q.url}return Y1(W.host,W.port,W.pathname)}async function CW($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await IO(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${yO}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(bO(V,$))})})().catch(Z)})}async function FB($){try{return(await CW($)).close(),!0}catch{return!1}}async function AB($,W){let Z=await H3($),Q=await CW(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function G3($){return $?JSON.parse(JSON.stringify($)):{}}function PW($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?G3(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function UB($,W){return $.error?.message??`hub command failed: ${W}`}function xO($){let W=G3($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function DB($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function gO($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function mO($){let W=G3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:xO($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class K3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new B1({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 W=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}),Z=PW(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return PW(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(UB(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,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}:{}},W);if(!J.ok)throw Error(UB(J,"session.restore"));let j=PW(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=gO(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>PW({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).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($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=mO(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).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($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.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 W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class F3{client;constructor($){this.client=new B1({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 W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{normalizeProviderId as Xm}from"@cline/llms";var D_={};w(D_,{LocalRuntimeHost:()=>b1});import{readdirSync as sg}from"node:fs";import{homedir as tg}from"node:os";import{isAbsolute as eg,join as RY,resolve as EY}from"node:path";import{captureSdkError as s$,createSessionId as $m,isLikelyAuthError as Wm,normalizeUserInput as Zm}from"@cline/shared";import{setHomeDirIfUnset as Qm}from"@cline/shared/storage";var rB={};w(rB,{saveProviderOAuthCredentials:()=>F2,resolveProviderApiKeyFromSettings:()=>w3,loginAndSaveProviderOAuthCredentials:()=>C4,isOAuthProvider:()=>K2,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderAuthStorageId:()=>N3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,formatProviderOAuthApiKey:()=>C3});import{decodeJwtPayload as fz,getClineEnvironmentConfig as lB}from"@cline/shared";var NB={};w(NB,{startClineDeviceAuth:()=>O3,refreshClineToken:()=>hW,loginClineOAuth:()=>O4,getValidClineCredentials:()=>z4,completeClineDeviceAuth:()=>z3});import{getClineEnvironmentConfig as D3}from"@cline/shared";var _B={};w(_B,{setSdkLogger:()=>U3,sdkDebug:()=>s,hashSecret:()=>N0,getSdkLogger:()=>cO});import{createHash as vO}from"node:crypto";var A3;function U3($){A3=$}function cO(){return A3}function N0($){if(typeof $!=="string"||$.length===0)return"unset";return vO("sha256").update($).digest("hex").slice(0,8)}function s($){try{A3?.debug($)}catch{}}R0();var fB={};w(fB,{startLocalOAuthServer:()=>H1});function uO(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function H1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??dO,j=uO(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dO=`<!DOCTYPE html>
279
279
  <html lang="en">
package/dist/index.js CHANGED
@@ -453,7 +453,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
453
453
  `)[0]?.trim())}function Z$($){if(!$)return;let W={...$},Z=i$(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function f6($){let W=Z$($.metadata)??{},Z=$.title!==void 0?i$($.title):J7($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function j7($){let W=D6($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=m5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function X7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:v5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function rB($,W,Z){jR(YR($),{recursive:!0}),XR($,`${JSON.stringify(X7({updatedAt:W,context:Z,messages:[]}),null,2)}
454
454
  `,"utf8")}function iB($,W){return h0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function nB($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}import{existsSync as KR}from"node:fs";import{readFile as FR}from"node:fs/promises";class L6{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function Q$($){let W=$?.trim();if(!W||!KR(W))return[];try{let Z=(await FR(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function Y7($){return $?{...$}:void 0}async function aB($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function T6($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function l0($){let W=T6($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function u5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function _R($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function B7($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function fR($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function LR($){return $.isSubagent!==!0&&!T6($.parentSessionId)}function TR($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function H7($){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 OR($){let W=B7($);if(W===0)return[];let Z=eB(),J=(await AR(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:TR(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=tB(Z,Y,`${Y}.json`),B=await sB(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=h0.safeParse(H);if(!G.success)return;return H7(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function zR($,W,Z){let Q=B7(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:fR(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(LR)).slice(0,Q)}function qR($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
455
455
  `).trim()}function oB($){return $.replace(/\s+/g," ").trim()}function MR($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function RR($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=oB(qR(Z.content));if(!Q)continue;let J=W==="user"?oB(UR(Q)):Q,j=DR(J.split(`
456
- `)[0]??J);return MR(j,50)}return}function ER($){let W=0;for(let Z of $)W+=u5(Z.metrics?.cost)??0;return W}function NR($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=l0(J.modelInfo?.provider);if(!Z)Z=l0(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function wR($){return l0($?.provider)??l0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function CR($){return l0($?.model)??l0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function V7($,W){let Z=_R($.metadata),Q=T6(W?.title)??T6(Z?.title),J=u5(W?.totalCost)??u5(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:l0(W?.provider)??l0($.provider)??wR(Z)??"",model:l0(W?.model)??l0($.model)??CR(Z)??"",metadata:j}}function PR($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function SR($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!PR(Z)}async function bR($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return SR(Z,Q)?{...Z,status:"idle"}:Z}))}async function yR($,W){return await Promise.all(W.map(async(Z)=>{let Q=V7(Z),J=Boolean(T6(Q.metadata?.title)),j=Boolean(l0(Q.provider)),X=Boolean(l0(Q.model)),Y=u5(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=NR(B),G=ER(B);return V7(Z,{title:J?void 0:RR(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function G7($,W={}){let Z=B7(W.limit),Q=W.includeSubagents===!0,J=await zR($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await OR(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await bR($,Y);if(W.hydrate===!1)return V.map((B)=>V7(B));return await yR($,V)}async function hR($){let W=$.trim();if(!W)return;let Z=tB(eB(),W,`${W}.json`),Q=await sB(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=h0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function kR($,W={}){let Z=new Map;return await G7({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(_6)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await hR(J);return await Q$(j)}},W)}import{captureSdkError as nK}from"@cline/shared";import{createSessionId as IE,isHubProtocolCompatible as xE,resolveClineBuildEnv as gE,resolveHubCommandTimeoutMs as mE}from"@cline/shared";import{spawn as KE}from"node:child_process";import{closeSync as FE,mkdirSync as AE,openSync as UE}from"node:fs";import{basename as DE,dirname as _E,join as fE}from"node:path";import{fileURLToPath as LE}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as TE,isHubDaemonProcess as FH,isHubProtocolCompatible as OE,resolveClineBuildEnv as AH,withResolvedClineBuildEnv as zE}from"@cline/shared";import{createHash as IR,randomBytes as xR}from"node:crypto";import{existsSync as gR}from"node:fs";import{chmod as mR,mkdir as K7,readFile as QH,rm as F7,writeFile as JH}from"node:fs/promises";import{dirname as jH,join as A7}from"node:path";import{resolveClineDataDir as z6,resolveClineDir as wp}from"@cline/shared/storage";var i2="0.0.62-nightly.1784171655";var O6={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:i2,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 vR="CLINE_HUB_DISCOVERY_PATH",cR="CLINE_HUB_BUILD_ID",WH=30000,uR=15000,dR=100;function lR($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function pR($){return IR("sha256").update($).digest("hex").slice(0,12)}function rR($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function XH(){return xR(32).toString("hex")}function iR($){return new Promise((W)=>setTimeout(W,$))}function nR($){return`${$}.lock`}async function aR($){try{let W=JSON.parse(await QH(A7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function ZH($){await F7($,{recursive:!0,force:!0}).catch(()=>{return})}function YH(){return process.env[cR]?.trim()||String(O6.version)}function n$($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${pR($)}`,Z=process.env[vR]?.trim()||A7(z6(),"locks","hub","owners",`${lR(W)}.json`);return{ownerId:W,discoveryPath:Z}}function Pp($=`hub-${Date.now().toString(36)}`){return n$($)}async function T0($){try{let W=JSON.parse(await QH($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function VH($,W){await K7(jH($),{recursive:!0}),await F7($,{force:!0}).catch(()=>{return}),await JH($,`${JSON.stringify(W,null,2)}
456
+ `)[0]??J);return MR(j,50)}return}function ER($){let W=0;for(let Z of $)W+=u5(Z.metrics?.cost)??0;return W}function NR($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=l0(J.modelInfo?.provider);if(!Z)Z=l0(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function wR($){return l0($?.provider)??l0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function CR($){return l0($?.model)??l0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function V7($,W){let Z=_R($.metadata),Q=T6(W?.title)??T6(Z?.title),J=u5(W?.totalCost)??u5(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:l0(W?.provider)??l0($.provider)??wR(Z)??"",model:l0(W?.model)??l0($.model)??CR(Z)??"",metadata:j}}function PR($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function SR($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!PR(Z)}async function bR($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return SR(Z,Q)?{...Z,status:"idle"}:Z}))}async function yR($,W){return await Promise.all(W.map(async(Z)=>{let Q=V7(Z),J=Boolean(T6(Q.metadata?.title)),j=Boolean(l0(Q.provider)),X=Boolean(l0(Q.model)),Y=u5(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=NR(B),G=ER(B);return V7(Z,{title:J?void 0:RR(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function G7($,W={}){let Z=B7(W.limit),Q=W.includeSubagents===!0,J=await zR($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await OR(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await bR($,Y);if(W.hydrate===!1)return V.map((B)=>V7(B));return await yR($,V)}async function hR($){let W=$.trim();if(!W)return;let Z=tB(eB(),W,`${W}.json`),Q=await sB(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=h0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function kR($,W={}){let Z=new Map;return await G7({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(_6)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await hR(J);return await Q$(j)}},W)}import{captureSdkError as nK}from"@cline/shared";import{createSessionId as IE,isHubProtocolCompatible as xE,resolveClineBuildEnv as gE,resolveHubCommandTimeoutMs as mE}from"@cline/shared";import{spawn as KE}from"node:child_process";import{closeSync as FE,mkdirSync as AE,openSync as UE}from"node:fs";import{basename as DE,dirname as _E,join as fE}from"node:path";import{fileURLToPath as LE}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as TE,isHubDaemonProcess as FH,isHubProtocolCompatible as OE,resolveClineBuildEnv as AH,withResolvedClineBuildEnv as zE}from"@cline/shared";import{createHash as IR,randomBytes as xR}from"node:crypto";import{existsSync as gR}from"node:fs";import{chmod as mR,mkdir as K7,readFile as QH,rm as F7,writeFile as JH}from"node:fs/promises";import{dirname as jH,join as A7}from"node:path";import{resolveClineDataDir as z6,resolveClineDir as wp}from"@cline/shared/storage";var i2="0.0.62";var O6={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:i2,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 vR="CLINE_HUB_DISCOVERY_PATH",cR="CLINE_HUB_BUILD_ID",WH=30000,uR=15000,dR=100;function lR($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function pR($){return IR("sha256").update($).digest("hex").slice(0,12)}function rR($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function XH(){return xR(32).toString("hex")}function iR($){return new Promise((W)=>setTimeout(W,$))}function nR($){return`${$}.lock`}async function aR($){try{let W=JSON.parse(await QH(A7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function ZH($){await F7($,{recursive:!0,force:!0}).catch(()=>{return})}function YH(){return process.env[cR]?.trim()||String(O6.version)}function n$($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${pR($)}`,Z=process.env[vR]?.trim()||A7(z6(),"locks","hub","owners",`${lR(W)}.json`);return{ownerId:W,discoveryPath:Z}}function Pp($=`hub-${Date.now().toString(36)}`){return n$($)}async function T0($){try{let W=JSON.parse(await QH($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function VH($,W){await K7(jH($),{recursive:!0}),await F7($,{force:!0}).catch(()=>{return}),await JH($,`${JSON.stringify(W,null,2)}
457
457
  `,{encoding:"utf8",mode:384}),await mR($,384)}async function W1($){await F7($,{force:!0}).catch(()=>{return})}async function BH($,W){let Z=nR($);await K7(jH(Z),{recursive:!0});let Q=Date.now()+uR;while(!0)try{await K7(Z,{recursive:!1}),await JH(A7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
458
458
  `,"utf8");try{return await W()}finally{await ZH(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await aR(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):WH+1;if(!X||!rR(X.pid)||Y>WH){await ZH(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await iR(dR)}}async function a$($,W){try{let Z=await fetch(W?.authToken?oR($):HH($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.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((J)=>typeof J==="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 R1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function HH($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function oR($){let W=new URL(HH($));return W.pathname="/status",W.toString()}function Sp($){return gR($)}import{CLINE_HUB_DEV_PORT as sR,CLINE_HUB_PORT as tR,resolveClineBuildEnv as eR}from"@cline/shared";var $E="CLINE_HUB_HOST",WE="CLINE_HUB_PORT",ZE="CLINE_HUB_PATHNAME",QE="127.0.0.1",JE=tR,jE="/hub";function GH($){return eR($)==="development"?sR:JE}function XE($={}){return($.env??process.env)[$E]?.trim()||QE}function d5($={}){let Z=($.env??process.env)[WE]?.trim();if(!Z)return GH($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return GH($);return Q}function YE($={}){return($.env??process.env)[ZE]?.trim()||jE}function J$($={},W={}){return{host:$.host??XE(W),port:$.port??d5(W),pathname:$.pathname??YE(W)}}import{join as VE}from"node:path";var BE="shared:cline",HE="CLINE_HUB_DISCOVERY_PATH",GE="hub-production";function gp($){let W=e1($.trim());return n$(`workspace:${W||$.trim()}`)}function E1($=BE){return n$($)}function j$(){return{ownerId:GE,discoveryPath:process.env[HE]?.trim()||VE(z6(),"locks","hub","production.json")}}var qE=8000,ME=200,RE=3000,EE=100,NE=[100,250,500,1000,2000],wE="--cline-hub-daemon";function CE($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function PE(){try{let $=fE(z6(),"logs","hub-daemon.log");return AE(_E($),{recursive:!0}),{fd:UE($,"a"),logPath:$}}catch{return}}function UH(){return AH()==="production"?j$():E1()}function o$($){return OE($).compatible}function KH($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function s$($,W){try{return await a$($,{authToken:W})}catch{return}}async function SE($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await s$($))?.url)return!0;await new Promise((J)=>setTimeout(J,EE))}return!1}async function l5($,W){if(await U7($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await SE($.url,RE);return await W1(W).catch(()=>{return}),Z}async function q6($,W){if(o$($))return!0;return l5($,W)}async function DH($){if(AH()!=="production")return;let W=E1();if(W.discoveryPath===$.discoveryPath)return;let Z=await T0(W.discoveryPath);if(Z?.url)await l5(Z,W.discoveryPath);else await W1(W.discoveryPath).catch(()=>{return})}function bE(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return LE(new URL(`./entry.${$}`,import.meta.url))}function yE($,W){let Z=bE(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=DE(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[wE]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...CE(W)],cwd:$,env:{...zE(process.env),CLINE_NO_INTERACTIVE:"1",[TE]:"1"}}}function hE($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function kE($,W={}){if(FH())return;let Z=yE($,W),Q=PE();try{KE(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)FE(Q.fd)}}async function p5($,W={}){for(let Z=0;;Z++)try{kE($,W);return}catch(Q){let J=NE[Z];if(!hE(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function _H($,W={}){if(FH())return;let Z=UH(),Q=J$(W),J=R1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;DH(Z).catch(()=>{return}).then(()=>T0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await l5(X,Z.discoveryPath)&&!j)return}else{let H=await s$(X.url,X.authToken);if(H?.url&&o$(H)&&await X$(H.url,{authToken:X.authToken}))return;if(H?.url)await q6({...H,authToken:X.authToken},Z.discoveryPath);else await W1(Z.discoveryPath).catch(()=>{return})}let V=await s$(J);if(V?.url){if(o$(V)){if(!j||!Y)return}else if(!await q6({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await p5($,B)}).catch(()=>{})}async function ap($,W={}){let Z=UH(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=J$(W),j=R1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)n2(F.url,F.authToken);return F};await DH(Z).catch(()=>{return});let Y=await T0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await l5(Y,Z.discoveryPath);else{let A=await s$(Y.url,F);if(A?.url&&o$(A)&&await X$(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await q6({...A,authToken:F},Z.discoveryPath);else await W1(Z.discoveryPath).catch(()=>{return})}}let B=await s$(j);if(B?.url){let F=KH(B,Y,j);if(o$(B))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" 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 q6(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await p5($,G);let K=Date.now()+qE;while(Date.now()<K){let F=await T0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await s$(F.url,F.authToken);if(D?.url&&o$(D)&&await X$(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await s$(j);if(A?.url&&!o$(A)){let D=KH(A,F,j);if(!await q6(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((D)=>setTimeout(D,ME))}throw Error("Timed out waiting for detached hub startup.")}function i5(){return gE()==="production"?j$():E1()}function vE(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function zH($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return zH($.data);return String($)}function cE($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function fH($){let W=$,Z=cE(W.reason);return new p0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:D7,{closeCode:W.code,closeReason:Z||void 0})}function uE($,W){if($ instanceof p0)return $;if($ instanceof Error)return new p0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new p0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new p0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new p0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var dE=8000,lE=200,LH="*",TH=8000,pE="cline-hub-auth.",qH=new Map,MH=new Set,rE=3000,iE=3000,nE=100,D7="Hub connection closed",aE=250,oE=5000,OH=0.5;class p0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function sE($){return $ instanceof p0}class r5 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function RH($,W){return $ instanceof r5&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function EH($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=L7($.toString());return Z?qH.get(Z):void 0}function tE($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function L7($){if(!tE($))return;let W=new URL(a2($));return W.search="",W.hash="",W.toString()}function _7($){let W=L7($);return!!W&&MH.has(W)}function n2($,W){let Z=L7($);if(Z){if(MH.add(Z),W?.trim())qH.set(Z,W)}return $}class N1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new p0("hub_connection_closed",D7);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),W=this.options.authToken?.trim()||EH($);$.hash="";let Q=new(vE())($.toString(),W?[`${pE}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new p0("hub_connect_timeout",`Timed out connecting to hub after ${TH}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},TH);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=uE(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=fH(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(zH(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=fH(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.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 j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=IE("hubreq_"),j=mE($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new r5($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===X6){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new u$(V,Y.error.message)}throw new r5($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!_7(this.currentUrl)||!sE($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await M6({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(aE*2**this.reconnectAttempt,oE),W=Math.round($*(1-OH)+Math.random()*$*OH);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!_7(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await M6({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 p0("hub_connection_closed",D7),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 p0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??LH}subscriptionSessionIdFromKey($){return $===LH?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function a2($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function X$($,W){let Z=new N1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function f7($,W){let Z=a2($),Q=await a$(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!xE(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await X$(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function eE($){let W=Date.now()+dE;while(Date.now()<W){let Z=await T0($.discoveryPath);if(Z?.url){let Q=await f7(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return n2(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,lE))}return}async function $N($){let W=Date.now()+iE;while(Date.now()<W){if(!(await a$($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,nE))}return!1}function WN($,W){try{return a2($)===a2(W)}catch{return!1}}function ZN($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function QN($,W,Z){let Q=new N1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:rE});return!ZN(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function T7($={}){if($.endpoint?.trim()){let J=await f7($.endpoint);return J.status==="compatible"?J.url:void 0}let W=i5(),Z=await T0(W.discoveryPath);if(!Z?.url)return;let Q=await f7(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return n2(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await W1(W.discoveryPath).catch(()=>{return});return}async function M6($={}){let W=await T7($);if(W&&await X$(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=i5();return await p5($.workspaceRoot??process.cwd()),await eE(Z)}async function U7($,W){let Z=new URL($),Q=W?.trim()||EH(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function JN($=i5()){let W=await T0($.discoveryPath);if(!W?.url)return!1;try{if(await U7(W.url,W.authToken))return!0}catch{}return!1}async function NH($){if(!_7($.url))return;let W=i5(),Z=await T0(W.discoveryPath);if(!Z?.url||!WN(Z.url,$.url))return;if(!await QN(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await JN())return;if(!await $N(Z.url))return;return await W1(W.discoveryPath).catch(()=>{return}),await M6({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveProviderRequestHeaders as KN}from"@cline/llms";import{captureSdkError as q7,createSessionId as yH,HUB_CHECKPOINT_CAPABILITY as FN,HUB_COMPACTION_CAPABILITY as AN,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as UN,HUB_HOOK_CAPABILITY_PREFIX as DN,HUB_MISTAKE_LIMIT_CAPABILITY as _N,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as fN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as LN,isHubToolExecutorName as TN}from"@cline/shared";import{createHash as jN}from"node:crypto";import{formatDisplayUserInput as wH}from"@cline/shared";import{z as B1}from"zod";function XN($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var YN=B1.custom(XN),n5=B1.object({version:B1.literal(1),updated_at:B1.string().datetime(),conversation_id:B1.string().min(1).optional(),source_message_count:B1.number().int().nonnegative(),source_prefix_hash:B1.string().min(1).optional(),source_last_message_key:B1.string().min(1).optional(),messages:B1.array(YN),system_prompt:B1.string().optional()});function O7($){return JSON.parse(JSON.stringify($))}function CH($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:wH($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:wH(W.text)}:W)}}function PH($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function VN($){let W=CH($);return PH(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function SH($){if(!$)return"";let W=CH($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(PH(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function bH($,W=$.length){let Z=jN("sha256");Z.update(`cline-session-compaction-source-v1
459
459
  `),Z.update(`${W}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cline/core",
3
3
  "description": "Cline Core SDK for Node Runtime",
4
- "version": "0.0.62-nightly.1784171655",
4
+ "version": "0.0.62",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/cline/cline",
@@ -48,9 +48,9 @@
48
48
  "test:watch": "vitest --config vitest.config.ts"
49
49
  },
50
50
  "dependencies": {
51
- "@cline/agents": "0.0.62-nightly.1784171655",
52
- "@cline/shared": "0.0.62-nightly.1784171655",
53
- "@cline/llms": "0.0.62-nightly.1784171655",
51
+ "@cline/agents": "0.0.62",
52
+ "@cline/shared": "0.0.62",
53
+ "@cline/llms": "0.0.62",
54
54
  "@modelcontextprotocol/sdk": "^1.29.0",
55
55
  "@opentelemetry/api": "^1.9.0",
56
56
  "@opentelemetry/api-logs": "^0.214.0",