@ai-agent-forge/agent-forge 0.85.1 → 0.85.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/bundle/.build-manifest.json +3 -3
- package/dist/bundle/chunks/{chunk-WJR4VZLQ.js → chunk-LQYV27QY.js} +3 -3
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +28 -9
- package/dist/core/sdk.js.map +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/extensions/with-deps/plugin.json +8 -8
- package/package.json +1 -1
|
@@ -1054,7 +1054,7 @@ ${body}
|
|
|
1054
1054
|
${args}`:skillBlock}catch(err2){return this._hostLogger?.error("session","skill expansion failed",{...this.sessionId===void 0?{}:{sessionId:this.sessionId},fields:{skill:skill.name,path:skill.filePath},cause:err2}),text}}async _queueUserInput(text,images,behavior,source){let processedInput=await this._runInputHandlers(text,images,source),expandedText=this._expandSkillCommand(processedInput.text);expandedText=expandPromptTemplate(expandedText,[...this.promptTemplates]),behavior==="steer"?await this._queueSteer(expandedText,processedInput.images):await this._queueFollowUp(expandedText,processedInput.images)}async steer(text,images,options){await this._queueUserInput(text,images,"steer",options?.source??"interactive")}async followUp(text,images,options){await this._queueUserInput(text,images,"followUp",options?.source??"interactive")}async _queueSteer(text,images){this._steeringMessages.push(text),this._emitQueueUpdate();let content=[{type:"text",text}];images&&content.push(...images),this.agent.steer({role:"user",content,timestamp:Date.now()})}async _queueFollowUp(text,images){this._followUpMessages.push(text),this._emitQueueUpdate();let content=[{type:"text",text}];images&&content.push(...images),this.agent.followUp({role:"user",content,timestamp:Date.now()})}async sendCustomMessage(message,options){let appMessage={role:"custom",customType:message.customType,content:message.content??[],display:message.display,details:message.details,timestamp:Date.now()};options?.deliverAs==="nextTurn"?this._pendingNextTurnMessages.push(appMessage):this.isStreaming&&options?.triggerTurn!==!1?options?.deliverAs==="followUp"?this.agent.followUp(appMessage):this.agent.steer(appMessage):options?.triggerTurn?await this._runAgentPrompt(appMessage):this.isStreaming?this._pendingCustomMessages.push(appMessage):this._appendCustomMessage(appMessage)}_appendCustomMessage(appMessage){this.agent.state.messages.push(appMessage),this.sessionManager.appendCustomMessageEntry(appMessage.customType,appMessage.content,appMessage.display,appMessage.details),this._emit({type:"message_start",message:appMessage}),this._emit({type:"message_end",message:appMessage})}_flushPendingCustomMessages(){if(this._pendingCustomMessages.length===0)return;let pending=this._pendingCustomMessages;this._pendingCustomMessages=[];for(let appMessage of pending)this._appendCustomMessage(appMessage)}async sendUserMessage(content,options){let text,images;if(typeof content=="string")text=content;else{let textParts=[];images=[];for(let part of content)part.type==="text"?textParts.push(part.text):images.push(part);text=textParts.join(`
|
|
1055
1055
|
`),images.length===0&&(images=void 0)}await this.prompt(text,{expandPromptTemplates:options?.expandPromptTemplates??!1,streamingBehavior:options?.deliverAs,images,source:"extension"})}clearQueue(){let steering=[...this._steeringMessages],followUp=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering,followUp}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(reason){this._pendingAbortReason=reason??"interrupted",this._lastAbortReason=this._pendingAbortReason,this._agentTaskScopeAbortController.abort(reason??"interrupted");try{await this._abortInternal(),this._appendTurnInterruptedMarker()}finally{this._pendingAbortReason=void 0,this._agentTaskScopeAbortController=new AbortController}}async _abortInternal(){this.abortRetry(),this._policyDecisionAbortController?.abort("session aborted"),this._commandAbortController?.abort("session aborted"),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort(),await this.waitForIdle()}_appendTurnInterruptedMarker(){let messages=this.agent.state.messages,last=messages[messages.length-1];if(last?.role==="custom"&&last.customType==="turn-interrupted")return;let lastAssistantAborted=!1;for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"){lastAssistantAborted=message.stopReason==="aborted";break}}lastAssistantAborted&&this._appendCustomMessage({role:"custom",customType:"turn-interrupted",content:"The previous turn was interrupted by the user before it completed.",display:!1,details:this._pendingAbortReason===void 0?void 0:{reason:this._pendingAbortReason},timestamp:Date.now()})}async _abortActiveCapabilityCommand(reason){this._commandAbortController?.abort(reason),await this._activeCapabilityCommand}async _cancelAndDrainForReload(){this.abortRetry(),this._policyDecisionAbortController?.abort("session reloaded"),this._commandAbortController?.abort("session reloaded"),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort(),await Promise.allSettled([this._activeCapabilityCommand,this._activeCompactionPromise,this._branchSummaryPromise,this._activeContextTransition,...this._activeBashPromises,this.waitForIdle()].filter(operation=>operation!==void 0)),await this._compactionQueue.catch(()=>{})}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async _emitModelSelect(nextModel,previousModel,source){return emitModelSelect(this._internal,nextModel,previousModel,source)}async setModel(model,options={}){return setModel(this._internal,model,options)}_addPersistedDefaultToNonEmptyScope(model){addPersistedDefaultToNonEmptyScope(this._internal,model)}async cycleModel(direction="forward",options={}){return cycleModel(this._internal,direction,options)}async _cycleScopedModel(direction,options){return cycleScopedModel(this._internal,direction,options)}async _cycleAvailableModel(direction,options){return cycleAvailableModel(this._internal,direction,options)}setThinkingLevel(level,options={}){let availableLevels=this.getAvailableThinkingLevels(),effectiveLevel=availableLevels.includes(level)?level:this._clampThinkingLevel(level,availableLevels),previousLevel=this.agent.state.thinkingLevel,isChanging=effectiveLevel!==previousLevel;this.agent.state.thinkingLevel=effectiveLevel,options.persist&&this.settingsManager.setDefaultThinkingLevel(level),isChanging&&(this.sessionManager.appendThinkingLevelChange(effectiveLevel),this._emit({type:"thinking_level_changed",level:effectiveLevel}),dispatchThinkingLevelSelectLifecycle(this._internal,effectiveLevel,previousLevel))}cycleThinkingLevel(options={}){if(!this.supportsThinking())return;let levels=this.getAvailableThinkingLevels(),nextIndex=(levels.indexOf(this.thinkingLevel)+1)%levels.length,nextLevel=levels[nextIndex];return this.setThinkingLevel(nextLevel,options),nextLevel}getAvailableThinkingLevels(){return this.model?getSupportedThinkingLevels(this.model):[...THINKING_LEVEL_OPTIONS]}supportsThinking(){return!!this.model?.reasoning}_getThinkingLevelForModelSwitch(targetModel,explicitLevel){return getThinkingLevelForModelSwitch(this._internal,targetModel,explicitLevel)}_clampThinkingLevel(level,_availableLevels){return this.model?clampThinkingLevel(this.model,level):"off"}syncQueueModesFromSettings(){this.agent.steeringMode=this.settingsManager.getSteeringMode(),this.agent.followUpMode=this.settingsManager.getFollowUpMode()}setSteeringMode(mode){this.agent.steeringMode=mode,this.settingsManager.setSteeringMode(mode)}setFollowUpMode(mode){this.agent.followUpMode=mode,this.settingsManager.setFollowUpMode(mode)}_enqueueCompaction(operation){return enqueueCompaction(this._internal,operation)}_observeLifecycleDeliveryError(error2,extensionPath,event){observeLifecycleDeliveryError(this._internal,error2,extensionPath,event)}async compact(customInstructions){if(this._reloadInProgress)throw new Error("Session reload in progress; compaction is unavailable");return this._enqueueCompaction(()=>this._compactInternal(customInstructions))}_compactInternal(customInstructions){return compactInternal(this._internal,customInstructions)}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}_checkCompaction(assistantMessage,skipAbortedCheck=!0,signal){return checkCompaction(this._internal,assistantMessage,skipAbortedCheck,signal)}_runAutoCompaction(reason,willRetry){return runAutoCompaction(this._internal,reason,willRetry)}setAutoCompactionEnabled(enabled){this.settingsManager.setCompactionEnabled(enabled)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async startSession(){await dispatchSessionStartLifecycle(this._internal,this._sessionStartEvent.reason,this._sessionStartEvent.previousSessionFile),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(reason){return extendResourcesFromExtensions(this._internal,reason)}buildExtensionResourcePaths(entries){return buildExtensionResourcePaths(this._internal,entries)}getExtensionSourceLabel(extensionPath){return getExtensionSourceLabel(extensionPath)}_refreshToolRegistry(options){refreshToolRegistry(this._internal,options)}_syncCapabilityTools(){syncCapabilityTools(this._internal)}_getCapabilitySkills(){return getCapabilitySkills(this._internal)}_getAvailableSkills(){let capabilitySkills=this._getCapabilitySkills();return capabilitySkills.length>0?capabilitySkills:this._resourceLoader.getSkills().skills}_validateCapabilitySkillConflicts(){validateCapabilitySkillConflicts(this._internal)}_refreshBootstrapSkills(){return refreshBootstrapSkills(this._internal)}async _disposeCapabilityPlugins(){let handles=Array.from(this._capabilityPlugins.values());this._isDisposingCapabilityPlugins=!0;let errors=[];try{for(let handle of handles)try{await handle.dispose()}catch(error2){errors.push(error2)}}finally{this._isDisposingCapabilityPlugins=!1}if(errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,"Capability plugin disposal failed")}_forwardLogRecordToHost(record){let hostLogger=this._hostLogger;if(!hostLogger)return;let context={...record.sessionId===void 0?{}:{sessionId:record.sessionId},...record.fields===void 0?{}:{fields:record.fields},...record.cause===void 0?{}:{cause:record.cause}};switch(record.level){case"debug":hostLogger.debug(record.pluginId,record.message,context);break;case"info":hostLogger.info(record.pluginId,record.message,context);break;case"warn":hostLogger.warn(record.pluginId,record.message,context);break;case"error":hostLogger.error(record.pluginId,record.message,context);break}}_buildRuntime(options){this._agentTaskScopeAbortController=new AbortController;let autoResizeImages=this.settingsManager.getImageAutoResize(),shellCommandPrefix=this.settingsManager.getShellCommandPrefix(),shellPath=this.settingsManager.getShellPath();this._capabilityRuntime=createCapabilityRuntime({apiVersion:EXPERIMENTAL_PUBLIC_API_VERSION,mode:this._capabilityMode,...this._agentDir===void 0?{}:{agentDir:this._agentDir},...this._communication===void 0?{}:{communication:this._communication},...this._turnContext===void 0?{}:{turnContext:this._turnContext},...this._roleAssociations===void 0?{}:{roleAssociations:this._roleAssociations},...this._memoryStorage===void 0?{}:{memoryStorage:this._memoryStorage},features:["tools","skills","logger-v1","diagnostics-v1","plugin-state-v1","runtime-inspector-v1","retry-policy","compaction-policy","overflow-policy","events","operations","rpc","context","provider-headers","credentials","commands","session","session-revision-v1","session-export","output-artifacts",...this._agentTaskAdapter||this._agentSessionReader||this._agentSessionLister?["agents"]:[],...this._agentTaskResults?["agent-result-replay-v1"]:[],...this._agentComposition?["agent-composition-v1"]:[],...this._interactionHost?["interaction"]:[]],transports:["in-process"]},{...this._agentTaskAdapter?{agents:this._agentTaskAdapter}:{},...this._agentTaskResults?{agentResults:this._agentTaskResults}:{},...this._agentSessionReader?{agentSessionReader:this._agentSessionReader}:{},...this._agentSessionLister?{agentSessionLister:this._agentSessionLister}:{},...this._agentComposition?{composition:this._agentComposition}:{},...this._interactionHost?{interaction:this._interactionHost}:{},parentSignal:()=>this._agentTaskScopeAbortController.signal,...this._traceService===void 0?{}:{trace:this._traceService},...this._modelRuntime?{modelRuntime:{getModelFacts:()=>{let model=this.agent.state.model;if(model)return{provider:model.provider,id:model.id,contextWindow:model.contextWindow??0,maxTokens:model.maxTokens??0,reasoning:model.reasoning??!1}},invoke:async(input,options2)=>{let model=this.agent.state.model;if(!model)throw new Error("No model is set on this session's agent");let authResult=await this._modelRuntime.getAuth(model,{...options2?.signal===void 0?{}:{signal:options2.signal}}),requestModel=authResult?.auth.baseUrl?{...model,baseUrl:authResult.auth.baseUrl}:model,context={...input.systemPrompt===void 0?{}:{systemPrompt:input.systemPrompt},messages:[{role:"user",content:[{type:"text",text:input.prompt}],timestamp:Date.now()}]},requestOptions={...input.maxTokens===void 0?{}:{maxTokens:input.maxTokens},...input.thinkingLevel&&input.thinkingLevel!=="off"&&model.reasoning?{reasoning:input.thinkingLevel}:{},...authResult?.auth.apiKey===void 0?{}:{apiKey:authResult.auth.apiKey},...authResult?.auth.headers===void 0?{}:{headers:authResult.auth.headers},...authResult?.env===void 0?{}:{env:authResult.env},...options2?.signal===void 0?{}:{signal:options2.signal}},response2=await(await this.agent.streamFunction(requestModel,context,requestOptions)).result();return response2.stopReason==="aborted"?{version:1,status:"aborted"}:response2.stopReason==="error"?{version:1,status:"failed",error:{code:"summary_provider_error",message:response2.errorMessage??"Unknown error"}}:response2.stopReason==="length"?{version:1,status:"failed",error:{code:"summary_length_cap",message:"generation hit the token cap"}}:{version:1,status:"completed",text:response2.content.filter(block=>block.type==="text").map(block=>block.text).join(""),usage:response2.usage}}}}:{},onOutputArtifactCommit:this._dispatchOutputArtifactCommit,onToolRegistryChange:()=>{this._suspendToolRegistryHookRefresh||!this._toolRegistryHookReady||(this._syncCapabilityTools(),this._refreshToolRegistry({activeToolNames:this.getActiveToolNames()}))},toolExecutionContext:{cwd:this._cwd},...this._hostLogger===void 0&&this._logRecordMirrorRef===void 0?{}:{onLogRecord:record=>{this._logRecordMirrorRef?.current?.(record),this._forwardLogRecordToHost(record)}},credentials:{resolve:async({providerId,minValidityMs,signal})=>{let result=await this._modelRuntime.getAuth(providerId,{signal,...minValidityMs===void 0?{}:{minOAuthValidityMs:minValidityMs}});if(result)return{...result.auth.apiKey===void 0?{}:{apiKey:result.auth.apiKey},headers:{...result.auth.headers??{}},...result.auth.baseUrl===void 0?{}:{baseUrl:result.auth.baseUrl},...result.source===void 0?{}:{source:result.source}}}},session:this.getSessionAPI()});let disabledBootstrap=this._disabledBootstrapPlugins,capabilityRuntime=this._capabilityRuntime,installBootstrap=(pluginId,install2)=>{if(!disabledBootstrap?.includes(pluginId))try{install2()}catch(error2){this._hostLogger?.error("session","bootstrap plugin load failed",{fields:{pluginId},cause:error2}),capabilityRuntime.recordPluginRejection(Object.freeze({code:"plugin_load_failed",manifestPath:"<embedded>",pluginId,message:error2 instanceof Error?error2.message:String(error2)})).catch(()=>{})}};installBootstrap(BOOTSTRAP_LIFECYCLE_PLUGIN_ID,()=>installBootstrapLifecycle(capabilityRuntime)),installBootstrap(BOOTSTRAP_AGENT_LOOP_PLUGIN_ID,()=>installBootstrapAgentLoop(capabilityRuntime,this._createLoopWiring())),installBootstrap(BOOTSTRAP_TOOLS_PLUGIN_ID,()=>installSessionBootstrapTools(capabilityRuntime,this._cwd,{read:{autoResizeImages},bash:{commandPrefix:shellCommandPrefix,shellPath},mode:this._capabilityMode},this._baseToolsOverride)),this._syncCapabilityTools(),installBootstrap(BOOTSTRAP_SKILLS_PLUGIN_ID,()=>(this._bootstrapSkillsHandle=installSessionBootstrapSkills(capabilityRuntime,this._resourceLoader.getSkills().skills),this._bootstrapSkillsHandle)),installBootstrap(BOOTSTRAP_RETRY_PLUGIN_ID,()=>installBootstrapRetryPolicy(capabilityRuntime)),installBootstrap(BOOTSTRAP_OVERFLOW_PLUGIN_ID,()=>installBootstrapOverflowPolicy(capabilityRuntime)),installBootstrap(BOOTSTRAP_COMPACTION_PLUGIN_ID,()=>installBootstrapCompactionPolicy(capabilityRuntime)),installBootstrap(BOOTSTRAP_BRANCH_SUMMARY_PLUGIN_ID,()=>installBootstrapBranchSummaryPolicy(capabilityRuntime)),this._syncCapabilityTools();let builtinToolNames=this._capabilityRuntime.listTools().filter(tool=>this._capabilityMode!=="readonly"||!tool.source.startsWith("agent-forge.builtin.")||tool.readonlySafe===!0).filter(tool=>this._capabilityMode!=="readonly"||!tool.source.startsWith("agent-forge.plugin.")||tool.readonlySafe===!0).map(tool=>tool.name),defaultActiveToolNames=this._baseToolsOverride?Object.keys(this._baseToolsOverride):this._capabilityMode==="readonly"?this._capabilityRuntime.listTools().filter(tool=>tool.readonlySafe).map(tool=>tool.name):["read","bash","edit","write"],baseActiveToolNames=[...options.activeToolNames??defaultActiveToolNames,...builtinToolNames];this._refreshToolRegistry({activeToolNames:baseActiveToolNames,includeAllExtensionTools:options.includeAllExtensionTools}),this._toolRegistryHookReady=!0}async reload(options){if(this._reloadInProgress)throw new Error("Session reload is already in progress");this._reloadInProgress=!0,this._beginContextTransitionFence(),this._bashEpoch+=1;let committedGeneration;try{await this._cancelAndDrainForReload();let oldCapabilityRuntime=this._capabilityRuntime,contextStrategyName=this._contextStrategyName,contextSnapshot,hasContextSnapshot=!1;if(contextStrategyName){if(!oldCapabilityRuntime?.hasContextStrategy(contextStrategyName))throw new Error(`Configured context strategy is not registered: ${contextStrategyName}`);contextSnapshot=await oldCapabilityRuntime.snapshotContext(contextStrategyName,this._copyContextMessages(this.agent.state.messages,contextStrategyName,"input"),{reason:"reload",sessionId:this.sessionId}),hasContextSnapshot=!0}let capabilityPluginPaths=Array.from(this._capabilityPlugins.keys()).filter(key=>!this._inlineCapabilityPlugins.has(key)),inlineCapabilityPlugins=Array.from(this._inlineCapabilityPlugins.values());await this._disposeCapabilityPlugins(),oldCapabilityRuntime?.revokeAllAPIs(),await oldCapabilityRuntime?.disposeAll(),await this._agentTaskAdapter?.dispose?.(),await this._interactionHost?.dispose?.(),await this._bootstrapToolsHandle?.dispose(),this._bootstrapToolsHandle=void 0,await this._bootstrapSkillsHandle?.dispose(),this._bootstrapSkillsHandle=void 0,await this._bootstrapRetryHandle?.dispose(),this._bootstrapRetryHandle=void 0,await this._bootstrapOverflowHandle?.dispose(),this._bootstrapOverflowHandle=void 0,await this._bootstrapCompactionHandle?.dispose(),this._bootstrapCompactionHandle=void 0,await this._bootstrapBranchSummaryHandle?.dispose(),this._bootstrapBranchSummaryHandle=void 0,await this._bootstrapAgentLoopHandle?.dispose(),this._bootstrapAgentLoopHandle=void 0,await this._bootstrapLifecycleHandle?.dispose(),this._bootstrapLifecycleHandle=void 0,await this.settingsManager.reload(),this.syncQueueModesFromSettings(),await this._resourceLoader.reload(),this._buildRuntime({activeToolNames:this.getActiveToolNames(),includeAllExtensionTools:!0});for(let manifestPath of capabilityPluginPaths)await this.loadCapabilityPluginManifest(manifestPath);for(let{manifest,factory}of inlineCapabilityPlugins)await this.loadCapabilityPlugin(manifest,factory);if(contextStrategyName&&hasContextSnapshot){if(!this._capabilityRuntime?.hasContextStrategy(contextStrategyName))throw new Error(`Configured context strategy is not registered after reload: ${contextStrategyName}`);await this._restoreContextTransition(contextSnapshot,"reload",{allowReload:!0})}await options?.beforeSessionStart?.(),await dispatchSessionStartLifecycle(this._internal,"reload"),await this.extendResourcesFromExtensions("reload"),committedGeneration=this._reloadGeneration+1,this._reloadGeneration=committedGeneration}finally{this._reloadInProgress=!1}if(committedGeneration===void 0)throw new Error("Session reload did not commit a generation");await this._dispatchSessionReloadLifecycle(committedGeneration)}_isRetryableError(message,execution,signal){return isRetryableError(this._internal,message,execution,signal)}_prepareRetry(message,precomputedDecision){return prepareRetry(this._internal,message,precomputedDecision)}abortRetry(){this._retryAbortController?.abort()}get isRetrying(){return this._retryAbortController!==void 0}get autoRetryEnabled(){return this.settingsManager.getRetryEnabled()}setAutoRetryEnabled(enabled){this.settingsManager.setRetryEnabled(enabled)}captureBashEpoch(){return captureBashEpoch(this._internal)}isBashEpochCurrent(epoch){return isBashEpochCurrent(this._internal,epoch)}emitUserBash(excludeFromContext){emitUserBash(this._internal,excludeFromContext)}async executeBash(command,onChunk,options){return executeBash(this._internal,command,onChunk,options)}recordBashResult(command,result,options){recordBashResult(this._internal,command,result,options)}abortBash(){abortBash(this._internal)}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){flushPendingBashMessages(this._internal)}setSessionName(name){this.sessionManager.appendSessionInfo(name);let event={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(event),dispatchSessionInfoChangedLifecycle(this._internal,event.name)}recordSuiteMismatch(originalSuiteId,currentSuiteId){this.sessionManager.appendCustomEntry(SUITE_MISMATCH_SESSION_ENTRY_TYPE,{originalSuiteId,currentSuiteId})}async navigateTree(targetId,options={}){return navigateTree(this._internal,targetId,options)}getUserMessagesForForking(){return getUserMessagesForForking(this._internal)}getSessionStats(){return getSessionStats(this._internal)}getContextUsage(){return getContextUsage(this._internal)}async exportToHtml(outputPath,options={}){return await exportToHtml(this._internal,outputPath,options)}exportToJsonl(outputPath){return exportToJsonl(this._internal,outputPath)}getLastAssistantText(){return getLastAssistantText(this._internal)}createReplacedSessionContext(){return{sendMessage:(message,options)=>this.sendCustomMessage(message,options),sendUserMessage:(content,options)=>this.sendUserMessage(content,options)}}get host(){let agent=this.agent,sessionManager=this.sessionManager;return{get abortSignal(){return agent.signal},get cwd(){return sessionManager.getCwd()},get sessionName(){return sessionManager.getSessionName()},get entries(){return sessionManager.getEntries()},setTransport:transport=>{agent.transport=transport},abortAgent:()=>{agent.abort()}}}};var import_semver4=__toESM(require_semver2(),1);import{existsSync as existsSync16,mkdirSync as mkdirSync11,rmSync as rmSync4,statSync as statSync13,writeFileSync as writeFileSync10}from"node:fs";import{dirname as dirname23,join as join42}from"node:path";var stdoutTakeoverState;var rawStdoutWriteTail=Promise.resolve();function getRawStdoutWrite(){return stdoutTakeoverState?stdoutTakeoverState.rawStdoutWrite:process.stdout.write.bind(process.stdout)}async function writeRawStdoutChunk(text){for(;;)try{await new Promise((resolve25,reject2)=>{try{getRawStdoutWrite()(text,error2=>{error2?reject2(error2):resolve25()})}catch(error2){reject2(error2 instanceof Error?error2:new Error(String(error2)))}});return}catch(error2){let writeError=error2 instanceof Error?error2:new Error(String(error2)),code=writeError.code;if(code!=="ENOBUFS"&&code!=="EAGAIN"&&code!=="EWOULDBLOCK")throw writeError;await new Promise(resolve25=>setTimeout(resolve25,10))}}function takeOverStdout(){if(stdoutTakeoverState)return;let rawStdoutWrite=process.stdout.write.bind(process.stdout),rawStderrWrite=process.stderr.write.bind(process.stderr),originalStdoutWrite=process.stdout.write;process.stdout.write=((chunk,encodingOrCallback,callback)=>typeof encodingOrCallback=="function"?rawStderrWrite(String(chunk),encodingOrCallback):rawStderrWrite(String(chunk),callback)),stdoutTakeoverState={rawStdoutWrite,rawStderrWrite,originalStdoutWrite}}function restoreStdout(){stdoutTakeoverState&&(process.stdout.write=stdoutTakeoverState.originalStdoutWrite,stdoutTakeoverState=void 0)}function isStdoutTakenOver(){return stdoutTakeoverState!==void 0}function writeRawStdout(text){text.length!==0&&(rawStdoutWriteTail=rawStdoutWriteTail.then(()=>writeRawStdoutChunk(text)),rawStdoutWriteTail.catch(()=>{process.exit(1)}))}async function waitForRawStdoutBackpressure(){for(;;){let tail=rawStdoutWriteTail;if(await tail,tail===rawStdoutWriteTail)return}}async function flushRawStdout(){await waitForRawStdoutBackpressure(),await writeRawStdoutChunk("")}var import_semver2=__toESM(require_semver2(),1);import{createHash as createHash8}from"node:crypto";import{chmodSync as chmodSync2,existsSync as existsSync13,mkdirSync as mkdirSync10,readdirSync as readdirSync11,readFileSync as readFileSync12,rmSync as rmSync3,writeFileSync as writeFileSync9}from"node:fs";import{basename as basename10,dirname as dirname20,join as join38,resolve as resolve12,sep as sep8}from"node:path";function getPackageTempFolder(agentDir){let tempFolder=join38(agentDir,"tmp","packages");return mkdirSync10(tempFolder,{recursive:!0,mode:448}),chmodSync2(tempFolder,448),tempFolder}function getNpmCommand(ctx){let configuredCommand=ctx.settingsManager.getNpmCommand();if(!configuredCommand||configuredCommand.length===0)return{command:"npm",args:[]};let[command,...args]=configuredCommand;if(!command)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command,args}}function getPackageManagerName(ctx){let npmCommand=getNpmCommand(ctx),commandParts=[npmCommand.command,...npmCommand.args],separatorIndex=commandParts.lastIndexOf("--"),packageManagerCommand=separatorIndex>=0?commandParts[separatorIndex+1]:npmCommand.command;return packageManagerCommand?basename10(packageManagerCommand).replace(/\.(cmd|exe)$/i,""):""}function getGitDependencyInstallArgs(ctx){let configuredCommand=ctx.settingsManager.getNpmCommand();return configuredCommand&&configuredCommand.length>0?["install"]:["install","--omit=dev"]}function getNpmInstallArgs(ctx,specs,installRoot){let packageManagerName=getPackageManagerName(ctx);return packageManagerName==="bun"?["install",...specs,"--cwd",installRoot,"--omit=peer"]:packageManagerName==="pnpm"?["install",...specs,"--prefix",installRoot,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...specs,"--prefix",installRoot,"--legacy-peer-deps"]}function getNpmInstallRoot(ctx,scope,temporary){return temporary?getTemporaryDir(ctx,"npm"):scope==="project"?join38(ctx.cwd,CONFIG_DIR_NAME,"npm"):join38(ctx.agentDir,"npm")}function getGitInstallRoot(ctx,scope){if(scope!=="temporary")return scope==="project"?join38(ctx.cwd,CONFIG_DIR_NAME,"git"):join38(ctx.agentDir,"git")}function getManagedNpmInstallPath(ctx,source,scope){return scope==="temporary"?join38(getTemporaryDir(ctx,"npm"),"node_modules",source.name):scope==="project"?join38(ctx.cwd,CONFIG_DIR_NAME,"npm","node_modules",source.name):join38(ctx.agentDir,"npm","node_modules",source.name)}function getGitInstallPath(ctx,source,scope){if(scope==="temporary")return getTemporaryDir(ctx,`git-${source.host}`,source.path);let installRoot=getGitInstallRoot(ctx,scope);if(!installRoot)throw new Error("Missing git install root");return resolveManagedPath(installRoot,source.host,source.path)}function getTemporaryDir(ctx,prefix,suffix){let root=resolveManagedPath(getPackageTempFolder(ctx.agentDir),prefix),hash=createHash8("sha256").update(`${prefix}-${suffix??""}`).digest("hex").slice(0,8);return resolveManagedPath(root,hash,suffix??"")}function resolveManagedPath(root,...parts){let resolvedRoot=resolve12(root),resolvedPath=resolve12(resolvedRoot,...parts);if(resolvedPath!==resolvedRoot&&!resolvedPath.startsWith(`${resolvedRoot}${sep8}`))throw new Error(`Refusing to use path outside package install root: ${resolvedPath}`);return resolvedPath}function ensureNpmProject(installRoot){existsSync13(installRoot)||mkdirSync10(installRoot,{recursive:!0}),markPathIgnoredByCloudSync(installRoot),ensureGitIgnore(installRoot);let packageJsonPath=join38(installRoot,"package.json");existsSync13(packageJsonPath)||writeFileSync9(packageJsonPath,JSON.stringify({name:"agent-forge-extensions",private:!0},null,2),"utf-8")}function ensureGitIgnore(dir){existsSync13(dir)||mkdirSync10(dir,{recursive:!0});let ignorePath=join38(dir,".gitignore");existsSync13(ignorePath)||writeFileSync9(ignorePath,`*
|
|
1056
1056
|
!.gitignore
|
|
1057
|
-
`,"utf-8")}function getInstalledNpmVersion(installedPath){let packageJsonPath=join38(installedPath,"package.json");if(existsSync13(packageJsonPath))try{let content=readFileSync12(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}function installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver2.satisfies)(installedVersion,source.range):!0:!1}function hasMissingGitDependencies(targetDir){let packageJsonPath=join38(targetDir,"package.json");if(!existsSync13(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync12(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve12(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve12(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep8}`)?!existsSync13(dependencyPath):!1})}catch{return!1}}function getGitUpdateMarkerPath(targetDir){return join38(dirname20(targetDir),`.${basename10(targetDir)}.agent-forge-update-incomplete`)}function pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve12(installRoot),current=dirname20(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync13(current)){current=dirname20(current);continue}if(readdirSync11(current).length>0)break;try{rmSync3(current,{recursive:!0,force:!0})}catch{break}current=dirname20(current)}}import{readFileSync as readFileSync13}from"node:fs";function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync13("/proc/self/environ","utf-8"),env2={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env2[entry.slice(0,idx)]=entry.slice(idx+1))}return env2}catch{return process.env}}function isOfflineModeEnabled2(){let value=process.env.AGENT_FORGE_OFFLINE;return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}async function runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index3=nextIndex;if(nextIndex+=1,index3>=tasks.length)return;results[index3]=await tasks[index3]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}import{existsSync as existsSync15,statSync as statSync12}from"node:fs";import{dirname as dirname22,join as join41,resolve as resolve14}from"node:path";var import_ignore3=__toESM(require_ignore(),1);import{existsSync as existsSync14,globSync,readdirSync as readdirSync12,readFileSync as readFileSync14,statSync as statSync11}from"node:fs";import{basename as basename11,dirname as dirname21,join as join39,relative as relative6,resolve as resolve13,sep as sep9}from"node:path";var RESOURCE_TYPES=["skills","prompts","themes"],FILE_PATTERNS={skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath3(p){return p.split(sep9).join("/")}function prefixIgnorePattern2(line,prefix){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative6(rootDir,dir),prefix=relativeDir?`${toPosixPath3(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join39(dir,filename);if(existsSync14(ignorePath))try{let patterns=readFileSync14(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve13(root,match2)).filter(path15=>relative6(root,path15).split(sep9).every(segment2=>segment2===".."||!segment2.startsWith("."))).sort((a,b2)=>a<b2?-1:a>b2?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync14(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync12(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync14(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!ig.ignores(relPath)&&(mode==="project"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}isDir&&(ig.ignores(`${relPath}/`)||entries.push(...collectSkillEntries(fullPath,mode,ig,root)))}}catch{}return entries}function collectAutoSkillEntries(dir,mode){return collectSkillEntries(dir,mode)}function findGitRepoRoot(startDir){let dir=resolve13(startDir);for(;;){if(existsSync14(join39(dir,".git")))return dir;let parent=dirname21(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve13(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join39(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname21(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function collectResourceFiles(dir,resourceType){return resourceType==="skills"?collectSkillEntries(dir,"project"):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentName=isSkillFile?basename11(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath3(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath3(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var import_semver3=__toESM(require_semver2(),1);import{homedir as homedir7}from"node:os";import{join as join40,relative as relative7}from"node:path";var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path15="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path15=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path15=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path15=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path15,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}function isExactNpmVersion(version){return(0,import_semver3.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver3.validRange)(version)??void 0:void 0}function getHomeDir(){return process.env.HOME||homedir7()}function getBaseDirForScope(ctx,scope){return scope==="project"?join40(ctx.cwd,CONFIG_DIR_NAME):scope==="user"?ctx.agentDir:ctx.cwd}function resolvePath3(ctx,input){return resolvePath(input,ctx.cwd,{homeDir:getHomeDir(),trim:!0})}function resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}function parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}function parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}function getPackageSourceString(pkg2){return typeof pkg2=="string"?pkg2:pkg2.source}function getSourceMatchKeyForInput(ctx,source){let parsed=parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${resolvePath3(ctx,parsed.path)}`}function getSourceMatchKeyForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}function buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}function findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg2 of configuredPackages){let sourceStr=getPackageSourceString(pkg2),parsed=parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}function normalizePackageSourceForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type!=="local")return source;let baseDir=getBaseDirForScope(ctx,scope),resolved=resolvePath3(ctx,parsed.path);return relative7(baseDir,resolved)||"."}function getPackageIdentity(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}return`local:${resolvePath3(ctx,parsed.path)}`}function dedupePackages(ctx,packages){let result=[],seen=new Map;for(let entry of packages){let identity=getPackageIdentity(ctx,getPackageSourceString(entry.pkg),entry.scope),index3=seen.get(identity);if(index3===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index3];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index3]=entry)}return result}import{readFileSync as readFileSync15}from"node:fs";var RESOURCE_FIELDS=["skills","prompts","themes"];function isObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg2=JSON.parse(stripBom(readFileSync15(packageJsonPath,"utf-8")));if(!isObject4(pkg2)||!isObject4(pkg2.pi))return null;let manifest={};for(let field2 of RESOURCE_FIELDS){let entries=pkg2.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}function resourcePrecedenceRank(m2){return m2.origin==="package"?4:(m2.scope==="project"?0:2)+(m2.source==="local"?0:1)}function collectPackageResources(packageRoot,accumulator,filter2,metadata){if(filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=getTargetMap(accumulator,resourceType);filter2.autoload===!1?applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}let manifest=readPiManifest(join41(packageRoot,"package.json"));if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];addManifestEntries(entries,packageRoot,resourceType,getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}function collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries){addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(target,f,metadata,!0)}}function applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=collectManifestFiles(packageRoot,resourceType);if(userPatterns.length===0){for(let f of allFiles)addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);addResource(target,f,metadata,enabled)}}function applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=collectManifestFiles(packageRoot,resourceType),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)addResource(target,filePath,metadata,enabled)}function collectManifestFiles(packageRoot,resourceType){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=collectFilesFromManifestEntries(entries,packageRoot,resourceType),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join41(packageRoot,resourceType);if(!existsSync15(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType);return{allFiles,enabledByManifest:new Set(allFiles)}}function addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=collectFilesFromManifestEntries(entries,root,resourceType),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&addResource(target,f,metadata,!0)}function collectFilesFromManifestEntries(entries,root,resourceType){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve14(root,entry)]);return collectFilesFromPaths(resolved,resourceType)}function resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>resolvePathFromBase(p,baseDir)),allFiles=collectFilesFromPaths(resolvedPlain,resourceType),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)addResource(target,f,metadata,enabledPaths.has(f))}function addAutoDiscoveredResources(cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[]},projectOverrides={skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[]},userDirs={skills:join41(globalBaseDir,"skills"),prompts:join41(globalBaseDir,"prompts"),themes:join41(globalBaseDir,"themes")},projectDirs={skills:join41(projectBaseDir,"skills"),prompts:join41(projectBaseDir,"prompts"),themes:join41(projectBaseDir,"themes")},userAgentsSkillsDir=join41(getHomeDir(),".agents","skills"),projectAgentsSkillDirs=collectAncestorAgentsSkillDirs(cwd).filter(dir=>resolve14(dir)!==resolve14(userAgentsSkillsDir)),addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=getTargetMap(accumulator,resourceType);for(let path15 of paths){let enabled=isEnabledByOverrides(path15,overrides,baseDir);addResource(target,path15,metadata,enabled)}};addResources("skills",collectAutoSkillEntries(projectDirs.skills,"project"),projectMetadata,projectOverrides.skills,projectBaseDir);for(let agentsSkillsDir of projectAgentsSkillDirs){let agentsBaseDir=dirname22(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addResources("skills",collectAutoSkillEntries(agentsSkillsDir,"agents"),agentsMetadata,projectOverrides.skills,agentsBaseDir)}addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("skills",collectAutoSkillEntries(userDirs.skills,"project"),userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname22(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addResources("skills",collectAutoSkillEntries(userAgentsSkillsDir,"agents"),userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir)}function collectFilesFromPaths(paths,resourceType){let files=[];for(let p of paths)if(existsSync15(p))try{let stats=statSync12(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType))}catch{}return files}function getTargetMap(accumulator,resourceType){switch(resourceType){case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;default:throw new Error(`Unknown resource type: ${resourceType}`)}}function addResource(map,path15,metadata,enabled){path15&&(map.has(path15)||map.set(path15,{metadata,enabled}))}function createAccumulator(){return{skills:new Map,prompts:new Map,themes:new Map}}function toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path15,{metadata,enabled}])=>({path:path15,enabled,metadata}));resolved.sort((a,b2)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b2.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes)}}var NETWORK_TIMEOUT_MS2=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4,DefaultPackageManager=class{cwd;agentDir;settingsManager;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}get context(){return{cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path15=this.getNpmInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="git"){let path15=this.getGitInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path15=this.resolvePathFromBase(parsed.path,baseDir);return existsSync16(path15)?path15:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);throw this.emitProgress({type:"error",action,source,message:errorMessage2}),error2}}async resolve(onMissing){let accumulator=createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join42(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}return addAutoDiscoveredResources(this.cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),toResolvedPaths(accumulator)}async resolveSourceResources(sources,options){let accumulator=createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg2 of globalSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg2 of projectSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync16(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg2 of globalSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg2 of projectSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled2()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=getManagedNpmInstallPath(this.context,source,scope),installedVersion=existsSync16(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled2())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync16(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync16(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg:pkg2,scope}of sources){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source,filter2=typeof pkg2=="object"?pkg2:void 0,deltaBase=this.findAutoloadDeltaBase(pkg2,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope),resolvedLocal=this.resolvePathFromBase(parsed.path,baseDir);if(existsSync16(resolvedLocal))try{statSync13(resolvedLocal).isDirectory()&&(metadata.baseDir=resolvedLocal,collectPackageResources(resolvedLocal,accumulator,filter2,metadata))}catch{}continue}let installMissing=async()=>{if(isOfflineModeEnabled2())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync16(installedPath)||!await installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync16(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled2()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg2,scope,sources){if(scope!=="project"||typeof pkg2!="object"||pkg2.autoload!==!1)return;let identity=this.getPackageIdentity(pkg2.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}parseSource(source){return parseSource(source)}getBaseDirForScope(scope){return getBaseDirForScope(this.context,scope)}resolvePath(input){return resolvePath3(this.context,input)}resolvePathFromBase(input,baseDir){return resolvePathFromBase(input,baseDir)}getPackageSourceString(pkg2){return getPackageSourceString(pkg2)}getSourceMatchKeyForInput(source){return getSourceMatchKeyForInput(this.context,source)}getSourceMatchKeyForSettings(source,scope){return getSourceMatchKeyForSettings(this.context,source,scope)}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){return normalizePackageSourceForSettings(this.context,source,scope)}getPackageIdentity(source,scope){return getPackageIdentity(this.context,source,scope)}dedupePackages(packages){return dedupePackages(this.context,packages)}buildNoMatchingPackageMessage(source,configuredPackages){return buildNoMatchingPackageMessage(source,configuredPackages)}getNpmCommand(){return getNpmCommand(this.context)}getInstalledNpmVersion(installedPath){return getInstalledNpmVersion(installedPath)}getGitInstallPath(source,scope){return getGitInstallPath(this.context,source,scope)}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled2())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}catch{return!1}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver4.maxSatisfying)(versions,range2):[...versions].sort(import_semver4.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled2())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2,env:{GIT_TERMINAL_PROMPT:"0"}})}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(getPackageManagerName(this.context)==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join42(dirname23(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(getPackageManagerName(this.context)!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path15=entry.dependencies?.[packageName]?.path;if(path15)return path15}}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join42(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=getManagedNpmInstallPath(this.context,source,scope);if(scope!=="user"||existsSync16(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync16(legacyPath)?legacyPath:managedPath}async installNpm(source,scope,temporary){let installRoot=getNpmInstallRoot(this.context,scope,temporary);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,[source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);if(!existsSync16(installRoot))return;let packageManagerName=getPackageManagerName(this.context);if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync16(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=getGitInstallRoot(this.context,scope);gitRoot&&ensureGitIgnore(gitRoot),mkdirSync11(dirname23(targetDir),{recursive:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}catch(error2){throw rmSync4(targetDir,{recursive:!0,force:!0}),pruneEmptyGitParents(targetDir,gitRoot),error2}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync16(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}async repairMissingGitDependencies(targetDir){hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error2){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error2}let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir}),rmSync4(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),markerPath=getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync16(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync10(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled2())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync4(targetDir,{recursive:!0,force:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0}),pruneEmptyGitParents(targetDir,getGitInstallRoot(this.context,scope))}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}spawnCommand(command,args,options){let env2=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env:env2})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env2=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env:env2})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,child.kill()},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error2=>{timeout&&clearTimeout(timeout),reject2(error2)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject2(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject2(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject2),child.on("exit",code=>{code===0?resolvePromise():reject2(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env2=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:env2});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{randomUUID as randomUUID15}from"crypto";import{existsSync as existsSync17,mkdirSync as mkdirSync12,readFileSync as readFileSync16,writeFileSync as writeFileSync11}from"fs";import{dirname as dirname24,join as join43}from"path";function isMergeableObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function deepMergeObjects(base,overrides){let result={...base};for(let key of Object.keys(overrides)){let overrideValue=overrides[key];if(overrideValue===void 0)continue;let baseValue=base[key];result[key]=isMergeableObject(baseValue)&&isMergeableObject(overrideValue)?deepMergeObjects(baseValue,overrideValue):overrideValue}return result}function deepMergeSettings(base,overrides){return deepMergeObjects(base,overrides)}function parseTimeoutSetting(value,settingName){let timeoutMs=parseHttpIdleTimeoutMs(value);if(timeoutMs!==void 0)return timeoutMs;if(value!==void 0)throw new Error(`Invalid ${settingName} setting: ${String(value)}`)}function toSettingsError(scope,error2,path15){return{scope,...path15?{path:path15}:{},error:error2 instanceof Error?error2:new Error(String(error2))}}var FileSettingsStorage=class{globalSettingsPath;projectSettingsPath;constructor(cwd,agentDir){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir);this.globalSettingsPath=join43(resolvedAgentDir,"settings.json"),this.projectSettingsPath=join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")}acquireLockSyncWithRetry(path15){let lastError;for(let attempt2=1;attempt2<=10;attempt2++)try{return import_proper_lockfile2.default.lockSync(path15,{realpath:!1})}catch(error2){if((typeof error2=="object"&&error2!==null&&"code"in error2?String(error2.code):void 0)!=="ELOCKED"||attempt2===10)throw error2;lastError=error2;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire settings lock")}withLock(scope,fn){let path15=scope==="global"?this.globalSettingsPath:this.projectSettingsPath,dir=dirname24(path15),release;try{let fileExists2=existsSync17(path15);fileExists2&&(release=this.acquireLockSyncWithRetry(path15));let current=fileExists2?readFileSync16(path15,"utf-8"):void 0,next=fn(current);next!==void 0&&(existsSync17(dir)||mkdirSync12(dir,{recursive:!0}),release||(release=this.acquireLockSyncWithRetry(path15)),writeFileSync11(path15,next,"utf-8"))}finally{release&&release()}}},InMemorySettingsStorage=class{global;project;withLock(scope,fn){let current=scope==="global"?this.global:this.project,next=fn(current);next!==void 0&&(scope==="global"?this.global=next:this.project=next)}},SettingsManager=class _SettingsManager{storage;globalSettings;projectSettings;settings;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(storage,initialGlobal,initialProject,globalLoadError=null,projectLoadError=null,initialErrors=[],settingsPaths={}){this.storage=storage,this.globalSettings=initialGlobal,this.projectSettings=initialProject,this.globalSettingsLoadError=globalLoadError,this.projectSettingsLoadError=projectLoadError,this.errors=[...initialErrors],this.settingsPaths=settingsPaths,this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}static create(cwd,agentDir=getAgentDir(),options={}){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),storage=new FileSettingsStorage(resolvedCwd,resolvedAgentDir);return _SettingsManager.fromStorageWithPaths(storage,options,{global:join43(resolvedAgentDir,"settings.json"),project:join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")})}static fromStorage(storage,options={}){return _SettingsManager.fromStorageWithPaths(storage,options)}static fromStorageWithPaths(storage,options,settingsPaths={}){let globalLoad=_SettingsManager.tryLoadFromStorage(storage,"global"),projectLoad=_SettingsManager.tryLoadFromStorage(storage,"project"),initialErrors=[];return globalLoad.error&&initialErrors.push(toSettingsError("global",globalLoad.error,settingsPaths.global)),projectLoad.error&&initialErrors.push(toSettingsError("project",projectLoad.error,settingsPaths.project)),new _SettingsManager(storage,globalLoad.settings,projectLoad.settings,globalLoad.error,projectLoad.error,initialErrors,settingsPaths)}static inMemory(settings2={},options={}){let storage=new InMemorySettingsStorage,initialSettings=_SettingsManager.migrateSettings(structuredClone(settings2));return storage.withLock("global",()=>JSON.stringify(initialSettings,null,2)),_SettingsManager.fromStorage(storage,options)}static loadFromStorage(storage,scope){let content;if(storage.withLock(scope,current=>{content=current}),!content)return{};let settings2=JSON.parse(stripBom(content));return _SettingsManager.migrateSettings(settings2)}static tryLoadFromStorage(storage,scope){try{return{settings:_SettingsManager.loadFromStorage(storage,scope),error:null}}catch(error2){return{settings:{},error:error2}}}static migrateSettings(settings2){if("queueMode"in settings2&&!("steeringMode"in settings2)&&(settings2.steeringMode=settings2.queueMode,delete settings2.queueMode),!("transport"in settings2)&&typeof settings2.websockets=="boolean"&&(settings2.transport=settings2.websockets?"websocket":"sse",delete settings2.websockets),"skills"in settings2&&typeof settings2.skills=="object"&&settings2.skills!==null&&!Array.isArray(settings2.skills)){let skillsSettings=settings2.skills;skillsSettings.enableSkillCommands!==void 0&&settings2.enableSkillCommands===void 0&&(settings2.enableSkillCommands=skillsSettings.enableSkillCommands),Array.isArray(skillsSettings.customDirectories)&&skillsSettings.customDirectories.length>0?settings2.skills=skillsSettings.customDirectories:delete settings2.skills}if("retry"in settings2&&typeof settings2.retry=="object"&&settings2.retry!==null&&!Array.isArray(settings2.retry)){let retrySettings=settings2.retry,providerSettings=typeof retrySettings.provider=="object"&&retrySettings.provider!==null?retrySettings.provider:void 0;typeof retrySettings.maxDelayMs=="number"&&(providerSettings?.maxRetryDelayMs===void 0||providerSettings?.maxRetryDelayMs===null)&&(retrySettings.provider={...providerSettings??{},maxRetryDelayMs:retrySettings.maxDelayMs}),delete retrySettings.maxDelayMs}return settings2}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let globalLoad=_SettingsManager.tryLoadFromStorage(this.storage,"global");globalLoad.error?(this.globalSettingsLoadError=globalLoad.error,this.recordError("global",globalLoad.error)):(this.globalSettings=globalLoad.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project");projectLoad.error?(this.projectSettingsLoadError=projectLoad.error,this.recordError("project",projectLoad.error)):(this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=null),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}applyOverrides(overrides){this.settings=deepMergeSettings(this.settings,overrides)}markModified(field2,nestedKey){this.modifiedFields.add(field2),nestedKey&&(this.modifiedNestedFields.has(field2)||this.modifiedNestedFields.set(field2,new Set),this.modifiedNestedFields.get(field2).add(nestedKey))}markProjectModified(field2,nestedKey){this.modifiedProjectFields.add(field2),nestedKey&&(this.modifiedProjectNestedFields.has(field2)||this.modifiedProjectNestedFields.set(field2,new Set),this.modifiedProjectNestedFields.get(field2).add(nestedKey))}recordError(scope,error2){this.errors.push(toSettingsError(scope,error2,this.settingsPaths[scope]))}clearModifiedScope(scope){if(scope==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(scope,task){this.writeQueue=this.writeQueue.then(()=>{task(),this.clearModifiedScope(scope)}).catch(error2=>{this.recordError(scope,error2)})}cloneModifiedNestedFields(source){let snapshot2=new Map;for(let[key,value]of source.entries())snapshot2.set(key,new Set(value));return snapshot2}persistScopedSettings(scope,snapshotSettings,modifiedFields,modifiedNestedFields){this.storage.withLock(scope,current=>{let currentFileSettings=current?_SettingsManager.migrateSettings(JSON.parse(stripBom(current))):{},mergedSettings={...currentFileSettings};for(let field2 of modifiedFields){let value=snapshotSettings[field2];if(modifiedNestedFields.has(field2)&&typeof value=="object"&&value!==null){let nestedModified=modifiedNestedFields.get(field2),baseNested=currentFileSettings[field2]??{},inMemoryNested=value,mergedNested={...baseNested};for(let nestedKey of nestedModified)mergedNested[nestedKey]=inMemoryNested[nestedKey];mergedSettings[field2]=mergedNested}else mergedSettings[field2]=value}return JSON.stringify(mergedSettings,null,2)})}save(){if(this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let snapshotGlobalSettings=structuredClone(this.globalSettings),modifiedFields=new Set(this.modifiedFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",snapshotGlobalSettings,modifiedFields,modifiedNestedFields)})}saveProjectSettings(settings2){if(this.projectSettings=structuredClone(settings2),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let snapshotProjectSettings=structuredClone(this.projectSettings),modifiedFields=new Set(this.modifiedProjectFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",snapshotProjectSettings,modifiedFields,modifiedNestedFields)})}updateProjectSettings(field2,update){let projectSettings=structuredClone(this.projectSettings);update(projectSettings),this.markProjectModified(field2),this.saveProjectSettings(projectSettings)}async flush(){await this.writeQueue}drainErrors(){let drained=[...this.errors];return this.errors=[],drained}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(version){this.globalSettings.lastChangelogVersion=version,this.markModified("lastChangelogVersion"),this.save()}getSuiteNoticeAcknowledgement(suiteId){return this.settings.suiteNoticesAcknowledged?.[suiteId]}setSuiteNoticeAcknowledgement(suiteId,ack){let next={...this.globalSettings.suiteNoticesAcknowledged??{},...this.settings.suiteNoticesAcknowledged??{}},existing=next[suiteId];next[suiteId]={...typeof existing=="object"&&existing!==null?existing:{},...ack.driftDigest===void 0?{}:{driftDigest:ack.driftDigest},...ack.upgradeRevision===void 0?{}:{upgradeRevision:ack.upgradeRevision}},this.globalSettings.suiteNoticesAcknowledged=next,this.settings.suiteNoticesAcknowledged=next,this.markModified("suiteNoticesAcknowledged"),this.save()}getSessionDir(){let sessionDir=this.settings.sessionDir;return sessionDir&&normalizePath(sessionDir)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}getMemoryModeSetting(){return this.settings.memory?.mode}setDefaultProvider(provider){this.globalSettings.defaultProvider=provider,this.markModified("defaultProvider"),this.save()}setDefaultModel(modelId){this.globalSettings.defaultModel=modelId,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(provider,modelId){this.globalSettings.defaultProvider=provider,this.globalSettings.defaultModel=modelId,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(mode){this.globalSettings.steeringMode=mode,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(mode){this.globalSettings.followUpMode=mode,this.markModified("followUpMode"),this.save()}getThemeSetting(){let value=this.settings.theme;if(typeof value=="string")return value}getTheme(){let theme2=this.getThemeSetting();return theme2?.includes("/")?void 0:theme2}setTheme(theme2){this.globalSettings.theme=theme2,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(level){this.globalSettings.defaultThinkingLevel=level,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(provider,modelId){return this.settings.modelThinkingLevels?.[`${provider}/${modelId}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(provider,modelId,level){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`]=level,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(provider,modelId){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(transport){this.globalSettings.transport=transport,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(enabled){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=enabled,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(enabled){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=enabled,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??5,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS}}getHttpIdleTimeoutMs(){return parseTimeoutSetting(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??DEFAULT_HTTP_IDLE_TIMEOUT_MS}setHttpIdleTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs)||timeoutMs<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(timeoutMs),this.markModified("httpIdleTimeoutMs"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){let configuredEditor=this.settings.externalEditor;if(typeof configuredEditor=="string"&&configuredEditor.trim()!=="")return configuredEditor;let environmentEditor=process.env.VISUAL||process.env.EDITOR;return environmentEditor||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(hide){this.globalSettings.hideThinkingBlock=hide,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(show){this.globalSettings.showCacheMissNotices=show,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){let shellPath=this.settings.shellPath;return shellPath&&normalizePath(shellPath)}setShellPath(path15){this.globalSettings.shellPath=path15,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(quiet){this.globalSettings.quietStartup=quiet,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(prefix){this.globalSettings.shellCommandPrefix=prefix,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(command){this.globalSettings.npmCommand=command?[...command]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(collapse){this.globalSettings.collapseChangelog=collapse,this.markModified("collapseChangelog"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(enabled){this.globalSettings.enableAnalytics=enabled,this.markModified("enableAnalytics"),enabled&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=randomUUID15(),this.markModified("trackingId")),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(packages){this.globalSettings.packages=packages,this.markModified("packages"),this.save()}setProjectPackages(packages){this.updateProjectSettings("packages",settings2=>{settings2.packages=packages})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(paths){this.globalSettings.skills=paths,this.markModified("skills"),this.save()}setProjectSkillPaths(paths){this.updateProjectSettings("skills",settings2=>{settings2.skills=paths})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(paths){this.globalSettings.prompts=paths,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(paths){this.updateProjectSettings("prompts",settings2=>{settings2.prompts=paths})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(paths){this.globalSettings.themes=paths,this.markModified("themes"),this.save()}setProjectThemePaths(paths){this.updateProjectSettings("themes",settings2=>{settings2.themes=paths})}setProjectSuite(id){this.updateProjectSettings("suite",settings2=>{if(id===void 0){delete settings2.suite;return}settings2.suite=id})}setSuite(id){id===void 0?delete this.globalSettings.suite:this.globalSettings.suite=id,this.markModified("suite"),this.save()}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(enabled){this.globalSettings.enableSkillCommands=enabled,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){let terminal=this.settings.terminal,images=terminal?.images;return{...images==="kitty"||images==="iterm2"?{images}:images===!1?{images:null}:{},...typeof terminal?.trueColor=="boolean"?{trueColor:terminal.trueColor}:{},...typeof terminal?.hyperlinks=="boolean"?{hyperlinks:terminal.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(show){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=show,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let width=this.settings.terminal?.imageWidthCells;return typeof width!="number"||!Number.isFinite(width)?60:Math.max(1,Math.floor(width))}setImageWidthCells(width){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(width)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){if(this.settings.terminal?.clearOnShrink!==void 0)return this.settings.terminal.clearOnShrink;let configuredValue=process.env.AGENT_FORGE_CLEAR_ON_SHRINK;return configuredValue===void 0?process.env.PI_CLEAR_ON_SHRINK==="1":configuredValue==="1"}setClearOnShrink(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=enabled,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=enabled,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":"regular"}setTuiMode(mode){this.globalSettings.tuiMode=mode,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(output){this.globalSettings.fullscreenExitOutput=output,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){let mode=this.settings.fullscreenScrollbar;return mode==="always"||mode==="hidden"?mode:"auto"}setFullscreenScrollbar(mode){this.globalSettings.fullscreenScrollbar=mode,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(enabled){this.globalSettings.fullscreenCopyOnSelect=enabled,this.markModified("fullscreenCopyOnSelect"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(enabled){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=enabled,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(blocked){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=blocked,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){let tools=this.settings.defaultTools;return tools?[...tools]:void 0}setEnabledModels(patterns){this.globalSettings.enabledModels=patterns,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(action){this.globalSettings.doubleEscapeAction=action,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let mode=this.settings.treeFilterMode;return mode&&["default","no-tools","user-only","labeled-only","all"].includes(mode)?mode:"default"}setTreeFilterMode(mode){this.globalSettings.treeFilterMode=mode,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){if(this.settings.showHardwareCursor!==void 0)return this.settings.showHardwareCursor;let configuredValue=process.env.AGENT_FORGE_HARDWARE_CURSOR;return configuredValue===void 0?process.env.PI_HARDWARE_CURSOR==="1":configuredValue==="1"}setShowHardwareCursor(enabled){this.globalSettings.showHardwareCursor=enabled,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(padding){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(padding))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===0?0:1}setOutputPad(padding){this.globalSettings.outputPad=padding,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(maxVisible){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(maxVisible))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){let mode=this.settings.markdown?.mermaid;return mode==="off"||mode==="final"?mode:"streaming"}setMermaidRenderingMode(mode){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=mode,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(warnings){this.globalSettings.warnings={...warnings},this.markModified("warnings"),this.save()}};import{existsSync as existsSync19,readdirSync as readdirSync13,readFileSync as readFileSync18,statSync as statSync15}from"node:fs";import{basename as basename12,dirname as dirname26,join as join45,resolve as resolve16,sep as sep10}from"node:path";import{execFile,spawnSync as spawnSync4}from"child_process";import{existsSync as existsSync18,readFileSync as readFileSync17,statSync as statSync14,unwatchFile,watchFile}from"fs";import{dirname as dirname25,join as join44,resolve as resolve15}from"path";function findGitPaths(cwd){let dir=cwd;for(;;){let gitPath=join44(dir,".git");if(existsSync18(gitPath))try{let stat5=statSync14(gitPath);if(stat5.isFile()){let content=readFileSync17(gitPath,"utf8").trim();if(content.startsWith("gitdir: ")){let gitDir=resolve15(dir,content.slice(8).trim()),headPath=join44(gitDir,"HEAD");if(!existsSync18(headPath))return null;let commonDirPath=join44(gitDir,"commondir"),commonGitDir=existsSync18(commonDirPath)?resolve15(gitDir,readFileSync17(commonDirPath,"utf8").trim()):gitDir;return{repoDir:dir,commonGitDir,headPath}}}else if(stat5.isDirectory()){let headPath=join44(gitPath,"HEAD");return existsSync18(headPath)?{repoDir:dir,commonGitDir:gitPath,headPath}:null}}catch{return null}let parent=dirname25(dir);if(parent===dir)return null;dir=parent}}function resolveBranchWithGitSync(repoDir){let result=spawnSync4("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return(result.status===0?result.stdout.trim():"")||null}function resolveBranchWithGitAsync(repoDir){return new Promise(resolvePromise=>{execFile("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8"},(error2,stdout)=>{if(error2){resolvePromise(null);return}let branch=stdout.trim();resolvePromise(branch||null)})})}function isWslEnvironment(){return process.platform==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)}function isWindowsMountedRepoPath(repoDir){return/^\/mnt\/[a-z](?:\/|$)/i.test(repoDir)}function shouldPollGitHead(repoDir){return isWslEnvironment()&&isWindowsMountedRepoPath(repoDir)}var FooterDataProvider=class _FooterDataProvider{cwd;static WATCH_DEBOUNCE_MS=500;cachedBranch=void 0;gitPaths=void 0;headWatcher=null;headWatchFilePath=null;headWatchFileListener=null;reftableWatcher=null;reftableTablesListWatcher=null;reftableTablesListPath=null;branchChangeCallbacks=new Set;availableProviderCount=0;refreshTimer=null;gitWatcherRetryTimer=null;refreshInFlight=!1;refreshPending=!1;disposed=!1;constructor(cwd){this.cwd=cwd,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher()}getGitBranch(){return this.cachedBranch===void 0&&(this.cachedBranch=this.resolveGitBranchSync()),this.cachedBranch}onBranchChange(callback){return this.branchChangeCallbacks.add(callback),()=>this.branchChangeCallbacks.delete(callback)}getAvailableProviderCount(){return this.availableProviderCount}setAvailableProviderCount(count){this.availableProviderCount=count}setCwd(cwd){this.cwd!==cwd&&(this.cwd=cwd,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.cachedBranch=void 0,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher(),this.notifyBranchChange())}dispose(){this.disposed=!0,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.branchChangeCallbacks.clear()}notifyBranchChange(){for(let cb of this.branchChangeCallbacks)cb()}scheduleRefresh(){if(!(this.disposed||this.refreshTimer)){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshGitBranchAsync()},_FooterDataProvider.WATCH_DEBOUNCE_MS)}}async refreshGitBranchAsync(){if(!this.disposed){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshInFlight=!0;try{let nextBranch=await this.resolveGitBranchAsync();if(this.disposed)return;if(this.cachedBranch!==void 0&&this.cachedBranch!==nextBranch){this.cachedBranch=nextBranch,this.notifyBranchChange();return}this.cachedBranch=nextBranch}finally{this.refreshInFlight=!1,this.refreshPending&&!this.disposed&&(this.refreshPending=!1,this.scheduleRefresh())}}}resolveGitBranchSync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?resolveBranchWithGitSync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}async resolveGitBranchAsync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?await resolveBranchWithGitAsync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}clearGitWatchers(){closeWatcher(this.headWatcher),this.headWatcher=null,this.headWatchFilePath&&this.headWatchFileListener&&(unwatchFile(this.headWatchFilePath,this.headWatchFileListener),this.headWatchFilePath=null,this.headWatchFileListener=null),closeWatcher(this.reftableWatcher),this.reftableWatcher=null,closeWatcher(this.reftableTablesListWatcher),this.reftableTablesListWatcher=null,this.reftableTablesListPath&&(unwatchFile(this.reftableTablesListPath),this.reftableTablesListPath=null),this.gitWatcherRetryTimer&&(clearTimeout(this.gitWatcherRetryTimer),this.gitWatcherRetryTimer=null)}scheduleGitWatcherRetry(){this.disposed||this.gitWatcherRetryTimer||(this.gitWatcherRetryTimer=setTimeout(()=>{this.gitWatcherRetryTimer=null,this.setupGitWatcher()},FS_WATCH_RETRY_DELAY_MS))}handleGitWatcherError(){this.clearGitWatchers(),this.scheduleGitWatcherRetry()}setupGitWatcher(){if(this.clearGitWatchers(),!this.gitPaths)return;let pollGitHead=shouldPollGitHead(this.gitPaths.repoDir);if(this.headWatcher=watchWithErrorHandler(dirname25(this.gitPaths.headPath),(_eventType,filename)=>{(!filename||filename==="HEAD")&&this.scheduleRefresh()},()=>this.handleGitWatcherError()),pollGitHead&&(this.headWatchFilePath=this.gitPaths.headPath,this.headWatchFileListener=(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()},watchFile(this.headWatchFilePath,{interval:1e3},this.headWatchFileListener)),!this.headWatcher&&!pollGitHead)return;let reftableDir=join44(this.gitPaths.commonGitDir,"reftable");if(existsSync18(reftableDir)){if(this.reftableWatcher=watchWithErrorHandler(reftableDir,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableWatcher)return;let tablesListPath=join44(reftableDir,"tables.list");if(existsSync18(tablesListPath)){if(this.reftableTablesListPath=tablesListPath,this.reftableTablesListWatcher=watchWithErrorHandler(tablesListPath,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableTablesListWatcher)return;watchFile(tablesListPath,{interval:250},(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()})}}}};function resolvePromptInput(input,description){if(input){if(existsSync19(input))try{return stripBom(readFileSync18(input,"utf-8"))}catch(error2){return console.error(source_default.yellow(`Warning: Could not read ${description} file ${input}: ${error2}`)),input}return input}}function loadContextFileFromDir(dir){let candidates=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(let filename of candidates){let filePath=join45(dir,filename);if(existsSync19(filePath))try{if(!statSync15(filePath).isFile())continue;return{path:filePath,content:stripBom(readFileSync18(filePath,"utf-8"))}}catch(error2){console.error(source_default.yellow(`Warning: Could not read ${filePath}: ${error2}`))}}return null}function findShadowedContextFile(cwd){let gitPaths=findGitPaths(cwd);if(!gitPaths)return;let commonGitDir=canonicalizePath(gitPaths.commonGitDir),worktreeRoot=canonicalizePath(gitPaths.repoDir),mainRepoRoot=dirname26(commonGitDir);if(!worktreeRoot.startsWith(`${mainRepoRoot}${sep10}`)||canonicalizePath(join45(mainRepoRoot,".git"))!==commonGitDir)return;let worktreeContextFile=loadContextFileFromDir(worktreeRoot);return worktreeContextFile?join45(mainRepoRoot,basename12(worktreeContextFile.path)):void 0}function loadProjectContextFiles(options){let resolvedCwd=resolvePath(options.cwd),resolvedAgentDir=resolvePath(options.agentDir),contextFiles=[],seenPaths=new Set,globalContext=loadContextFileFromDir(resolvedAgentDir);globalContext&&(contextFiles.push(globalContext),seenPaths.add(globalContext.path));let ancestorContextFiles=[],shadowedContextFile=findShadowedContextFile(resolvedCwd),currentDir=resolvedCwd;for(;;){let contextFile=loadContextFileFromDir(currentDir),isShadowed=shadowedContextFile!==void 0&&canonicalizePath(contextFile?.path??"")===shadowedContextFile;contextFile&&!isShadowed&&!seenPaths.has(contextFile.path)&&(ancestorContextFiles.unshift(contextFile),seenPaths.add(contextFile.path));let parentDir=dirname26(currentDir);if(parentDir===currentDir)break;currentDir=parentDir}return contextFiles.push(...ancestorContextFiles),contextFiles}var DefaultResourceLoader=class{cwd;agentDir;settingsManager;packageManager;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager??SettingsManager.create(this.cwd,this.agentDir),this.packageManager=new DefaultPackageManager({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}),this.additionalSkillPaths=options.additionalSkillPaths??[],this.additionalPromptTemplatePaths=options.additionalPromptTemplatePaths??[],this.additionalThemePaths=options.additionalThemePaths??[],this.noSkills=options.noSkills??!1,this.noPromptTemplates=options.noPromptTemplates??!1,this.noThemes=options.noThemes??!1,this.noContextFiles=options.noContextFiles??!1,this.systemPromptSource=options.systemPrompt,this.appendSystemPromptSource=options.appendSystemPrompt,this.skillsOverride=options.skillsOverride,this.promptsOverride=options.promptsOverride,this.themesOverride=options.themesOverride,this.agentsFilesOverride=options.agentsFilesOverride,this.systemPromptOverride=options.systemPromptOverride,this.appendSystemPromptOverride=options.appendSystemPromptOverride,this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[]}getSkills(){return{skills:this.skills.slice(),diagnostics:this.skillDiagnostics.slice()}}getPrompts(){return{prompts:this.prompts.slice(),diagnostics:this.promptDiagnostics.slice()}}getThemes(){return{themes:this.themes.slice(),diagnostics:this.themeDiagnostics.slice()}}getAgentsFiles(){return{agentsFiles:this.agentsFiles.slice()}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(path15=>({path:path15}))}extendResources(paths){let skillPaths=this.normalizeExtensionPaths(paths.skillPaths??[]),promptPaths=this.normalizeExtensionPaths(paths.promptPaths??[]),themePaths=this.normalizeExtensionPaths(paths.themePaths??[]);for(let entry of skillPaths)this.extensionSkillSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of promptPaths)this.extensionPromptSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of themePaths)this.extensionThemeSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));skillPaths.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,skillPaths.map(entry=>entry.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),promptPaths.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,promptPaths.map(entry=>entry.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),themePaths.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,themePaths.map(entry=>entry.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async reload(_options){await this.settingsManager.reload();let resolvedPaths=await this.packageManager.resolve();this.resourceMetadataByPath=new Map;let metadataByPath=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;let getEnabledResources=resources=>{for(let r of resources)metadataByPath.has(r.path)||metadataByPath.set(r.path,r.metadata);return resources.filter(r=>r.enabled)},getEnabledPaths=resources=>getEnabledResources(resources).map(r=>r.path),enabledSkillResources=getEnabledResources(resolvedPaths.skills),enabledPrompts=getEnabledPaths(resolvedPaths.prompts),enabledThemes=getEnabledPaths(resolvedPaths.themes),enabledSkills=enabledSkillResources.map(resource=>this.mapSkillPath(resource,metadataByPath)),skillPaths=this.noSkills?[...this.additionalSkillPaths]:this.mergePaths(enabledSkills,this.additionalSkillPaths);this.lastSkillPaths=skillPaths,this.updateSkillsFromPaths(skillPaths,metadataByPath);for(let p of this.additionalSkillPaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.skillDiagnostics.some(d2=>d2.path===resolved)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:resolved})}let promptPaths=this.noPromptTemplates?[...this.additionalPromptTemplatePaths]:this.mergePaths(enabledPrompts,this.additionalPromptTemplatePaths);this.lastPromptPaths=promptPaths,this.updatePromptsFromPaths(promptPaths,metadataByPath);for(let p of this.additionalPromptTemplatePaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.promptDiagnostics.some(d2=>d2.path===resolved)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:resolved})}let themePaths=this.noThemes?[...this.additionalThemePaths]:this.mergePaths(enabledThemes,this.additionalThemePaths);this.lastThemePaths=themePaths,this.updateThemesFromPaths(themePaths,metadataByPath);for(let p of this.additionalThemePaths){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.themeDiagnostics.some(d2=>d2.path===resolved)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:resolved})}let agentsFiles={agentsFiles:this.noContextFiles?[]:loadProjectContextFiles({cwd:this.cwd,agentDir:this.agentDir})},resolvedAgentsFiles=this.agentsFilesOverride?this.agentsFilesOverride(agentsFiles):agentsFiles;this.agentsFiles=resolvedAgentsFiles.agentsFiles;let systemPromptSource=this.systemPromptSource??this.discoverSystemPromptFile(),baseSystemPrompt=resolvePromptInput(systemPromptSource,"system prompt");this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(baseSystemPrompt):baseSystemPrompt,this.systemPromptSourcePath=systemPromptSource&&existsSync19(systemPromptSource)?resolvePath(systemPromptSource):void 0;let appendSources=this.appendSystemPromptSource;if(!appendSources){let discoveredAppendSystemPromptFile=this.discoverAppendSystemPromptFile();appendSources=discoveredAppendSystemPromptFile?[discoveredAppendSystemPromptFile]:[]}let baseAppend=appendSources.map(s=>resolvePromptInput(s,"append system prompt")).filter(s=>s!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(baseAppend):baseAppend,this.appendSystemPromptSourcePaths=appendSources.filter(source=>existsSync19(source)).map(source=>resolvePath(source))}mapSkillPath(resource,metadataByPath){if(resource.metadata.source!=="auto"&&resource.metadata.origin!=="package")return resource.path;try{if(!statSync15(resource.path).isDirectory())return resource.path}catch{return resource.path}let skillFile=join45(resource.path,"SKILL.md");return existsSync19(skillFile)?(metadataByPath.has(skillFile)||metadataByPath.set(skillFile,resource.metadata),skillFile):resource.path}normalizeExtensionPaths(entries){return entries.map(entry=>{let metadata=entry.metadata.baseDir?{...entry.metadata,baseDir:this.resolveResourcePath(entry.metadata.baseDir)}:entry.metadata;return{path:this.resolveResourcePath(entry.path),metadata}})}updateSkillsFromPaths(skillPaths,metadataByPath){let skillsResult;this.noSkills&&skillPaths.length===0?skillsResult={skills:[],diagnostics:[]}:skillsResult=loadSkills({cwd:this.cwd,agentDir:this.agentDir,skillPaths,includeDefaults:!1});let applySourceInfo=skill=>({...skill,sourceInfo:this.findSourceInfoForPath(skill.filePath,this.extensionSkillSourceInfos,metadataByPath)??skill.sourceInfo??this.getDefaultSourceInfoForPath(skill.filePath)});skillsResult={skills:skillsResult.skills.map(applySourceInfo),diagnostics:skillsResult.diagnostics};let resolvedSkills=this.skillsOverride?this.skillsOverride(skillsResult):skillsResult;this.skills=resolvedSkills.skills.map(applySourceInfo),this.skillDiagnostics=resolvedSkills.diagnostics}updatePromptsFromPaths(promptPaths,metadataByPath){let promptsResult;if(this.noPromptTemplates&&promptPaths.length===0)promptsResult={prompts:[],diagnostics:[]};else{let allPrompts=loadPromptTemplates({cwd:this.cwd,agentDir:this.agentDir,promptPaths,includeDefaults:!1});promptsResult=this.dedupePrompts(allPrompts)}let resolvedPrompts=this.promptsOverride?this.promptsOverride(promptsResult):promptsResult;this.prompts=resolvedPrompts.prompts.map(prompt=>({...prompt,sourceInfo:this.findSourceInfoForPath(prompt.filePath,this.extensionPromptSourceInfos,metadataByPath)??prompt.sourceInfo??this.getDefaultSourceInfoForPath(prompt.filePath)})),this.promptDiagnostics=resolvedPrompts.diagnostics}updateThemesFromPaths(themePaths,metadataByPath){let loadedThemes,themeDiagnostics;if(this.noThemes&&themePaths.length===0)loadedThemes=[],themeDiagnostics=[];else{let loaded=this.loadThemes(themePaths,!1),deduped=this.dedupeThemes(loaded.themes);loadedThemes=deduped.themes,themeDiagnostics=[...loaded.diagnostics,...deduped.diagnostics]}let themesResult={themes:loadedThemes.map(theme2=>this.buildThemeMeta(theme2,metadataByPath)),diagnostics:themeDiagnostics},resolvedThemes=this.themesOverride?this.themesOverride(themesResult):themesResult;this.themes=resolvedThemes.themes.map(meta=>this.buildThemeMeta(meta,metadataByPath)),this.themeDiagnostics=resolvedThemes.diagnostics}buildThemeMeta(source,metadataByPath){let sourcePath=source.sourcePath??"";return{name:source.name,sourcePath,sourceInfo:sourcePath?this.findSourceInfoForPath(sourcePath,this.extensionThemeSourceInfos,metadataByPath)??source.sourceInfo??this.getDefaultSourceInfoForPath(sourcePath):source.sourceInfo}}findSourceInfoForPath(resourcePath,extraSourceInfos,metadataByPath){if(!resourcePath)return;if(resourcePath.startsWith("<"))return this.getDefaultSourceInfoForPath(resourcePath);let normalizedResourcePath=resolve16(resourcePath);if(extraSourceInfos)for(let[sourcePath,sourceInfo]of extraSourceInfos.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return{...sourceInfo,path:resourcePath}}if(metadataByPath){let exact=metadataByPath.get(normalizedResourcePath)??metadataByPath.get(resourcePath);if(exact)return createSourceInfo(resourcePath,exact);for(let[sourcePath,metadata]of metadataByPath.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return createSourceInfo(resourcePath,metadata)}}}getDefaultSourceInfoForPath(filePath){if(filePath.startsWith("<")&&filePath.endsWith(">"))return{path:filePath,source:filePath.slice(1,-1).split(":")[0]||"temporary",scope:"temporary",origin:"top-level"};let normalizedPath=resolve16(filePath),agentRoots=[join45(this.agentDir,"skills"),join45(this.agentDir,"prompts"),join45(this.agentDir,"themes")],projectRoots=[join45(this.cwd,CONFIG_DIR_NAME,"skills"),join45(this.cwd,CONFIG_DIR_NAME,"prompts"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let root of agentRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"user",origin:"top-level",baseDir:root};for(let root of projectRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"project",origin:"top-level",baseDir:root};return{path:filePath,source:"local",scope:"temporary",origin:"top-level",baseDir:statSync15(normalizedPath).isDirectory()?normalizedPath:resolve16(normalizedPath,"..")}}mergePaths(primary,additional){let merged=[],seen=new Set;for(let p of[...primary,...additional]){let resolved=this.resolveResourcePath(p),canonicalPath=canonicalizePath(resolved);seen.has(canonicalPath)||(seen.add(canonicalPath),merged.push(resolved))}return merged}resolveResourcePath(p){return resolvePath(p,this.cwd,{trim:!0})}loadThemes(paths,includeDefaults=!0){let themes=[],diagnostics=[];if(includeDefaults){let defaultDirs=[join45(this.agentDir,"themes"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let dir of defaultDirs)this.loadThemesFromDir(dir,themes,diagnostics)}for(let p of paths){let resolved=this.resolveResourcePath(p);if(!existsSync19(resolved)){diagnostics.push({type:"warning",message:"theme path does not exist",path:resolved});continue}try{let stats=statSync15(resolved);stats.isDirectory()?this.loadThemesFromDir(resolved,themes,diagnostics):stats.isFile()&&resolved.endsWith(".json")?this.loadThemeFromFile(resolved,themes,diagnostics):diagnostics.push({type:"warning",message:"theme path is not a json file",path:resolved})}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme path";diagnostics.push({type:"warning",message,path:resolved})}}return{themes,diagnostics}}loadThemesFromDir(dir,themes,diagnostics){if(existsSync19(dir))try{let entries=readdirSync13(dir,{withFileTypes:!0});for(let entry of entries){let isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync15(join45(dir,entry.name)).isFile()}catch{continue}isFile&&entry.name.endsWith(".json")&&this.loadThemeFromFile(join45(dir,entry.name),themes,diagnostics)}}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme directory";diagnostics.push({type:"warning",message,path:dir})}}loadThemeFromFile(filePath,themes,diagnostics){try{themes.push(loadThemeFromPath(filePath))}catch(error2){let message=error2 instanceof Error?error2.message:"failed to load theme";diagnostics.push({type:"warning",message,path:filePath})}}dedupePrompts(prompts){let seen=new Map,diagnostics=[];for(let prompt of prompts){let existing=seen.get(prompt.name);existing?diagnostics.push({type:"collision",message:`name "/${prompt.name}" collision`,path:prompt.filePath,collision:{resourceType:"prompt",name:prompt.name,winnerPath:existing.filePath,loserPath:prompt.filePath}}):seen.set(prompt.name,prompt)}return{prompts:Array.from(seen.values()),diagnostics}}dedupeThemes(themes){let seen=new Map,diagnostics=[];for(let t of themes){let name=t.name??"unnamed",existing=seen.get(name);existing?diagnostics.push({type:"collision",message:`name "${name}" collision`,path:t.sourcePath,collision:{resourceType:"theme",name,winnerPath:existing.sourcePath??"<builtin>",loserPath:t.sourcePath??"<builtin>"}}):seen.set(name,t)}return{themes:Array.from(seen.values()),diagnostics}}discoverSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"SYSTEM.md");if(existsSync19(globalPath))return globalPath}discoverAppendSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"APPEND_SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"APPEND_SYSTEM.md");if(existsSync19(globalPath))return globalPath}isUnderPath(target,root){let normalizedRoot=resolve16(root);if(target===normalizedRoot)return!0;let prefix=normalizedRoot.endsWith(sep10)?normalizedRoot:`${normalizedRoot}${sep10}`;return target.startsWith(prefix)}};import{existsSync as existsSync23,mkdirSync as mkdirSync15,readFileSync as readFileSync20,writeFileSync as writeFileSync12}from"node:fs";import{isAbsolute as isAbsolute10,join as join50,relative as relative8,sep as sep11}from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{existsSync as existsSync22,realpathSync as realpathSync4}from"node:fs";import{readFile as readFile9}from"node:fs/promises";import{join as join49,resolve as resolve18}from"node:path";var import_semver5=__toESM(require_semver2(),1);var BUILTIN_CAPABILITY_PACKAGE_IDS=Object.freeze({"builtin.goal":"agent-forge.plugin.goal","builtin.plan":"agent-forge.plugin.plan","builtin.todo-set":"agent-forge.plugin.todo-set","builtin.session-share":"agent-forge.plugin.session-share","builtin.subagent-delegate":"agent-forge.plugin.subagent-delegate","builtin.memory":"agent-forge.plugin.memory"});function resolveBuiltinCapabilities(shortIds){let unknownShortIds=[],seen=new Set;for(let shortId of shortIds)shortId in BUILTIN_CAPABILITY_PACKAGE_IDS||seen.has(shortId)||(seen.add(shortId),unknownShortIds.push(shortId));return{registrations:Object.freeze([]),unknownShortIds:Object.freeze(unknownShortIds)}}import{constants as constants7,copyFileSync,existsSync as existsSync21,mkdirSync as mkdirSync13}from"node:fs";import{basename as basename13,join as join46,parse as parse4,resolve as resolve17}from"node:path";import{existsSync as existsSync20}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync20(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
|
|
1057
|
+
`,"utf-8")}function getInstalledNpmVersion(installedPath){let packageJsonPath=join38(installedPath,"package.json");if(existsSync13(packageJsonPath))try{let content=readFileSync12(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}function installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver2.satisfies)(installedVersion,source.range):!0:!1}function hasMissingGitDependencies(targetDir){let packageJsonPath=join38(targetDir,"package.json");if(!existsSync13(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync12(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve12(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve12(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep8}`)?!existsSync13(dependencyPath):!1})}catch{return!1}}function getGitUpdateMarkerPath(targetDir){return join38(dirname20(targetDir),`.${basename10(targetDir)}.agent-forge-update-incomplete`)}function pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve12(installRoot),current=dirname20(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync13(current)){current=dirname20(current);continue}if(readdirSync11(current).length>0)break;try{rmSync3(current,{recursive:!0,force:!0})}catch{break}current=dirname20(current)}}import{readFileSync as readFileSync13}from"node:fs";function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync13("/proc/self/environ","utf-8"),env2={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env2[entry.slice(0,idx)]=entry.slice(idx+1))}return env2}catch{return process.env}}function isOfflineModeEnabled2(){let value=process.env.AGENT_FORGE_OFFLINE;return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}async function runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index3=nextIndex;if(nextIndex+=1,index3>=tasks.length)return;results[index3]=await tasks[index3]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}import{existsSync as existsSync15,statSync as statSync12}from"node:fs";import{dirname as dirname22,join as join41,resolve as resolve14}from"node:path";var import_ignore3=__toESM(require_ignore(),1);import{existsSync as existsSync14,globSync,readdirSync as readdirSync12,readFileSync as readFileSync14,statSync as statSync11}from"node:fs";import{basename as basename11,dirname as dirname21,join as join39,relative as relative6,resolve as resolve13,sep as sep9}from"node:path";var RESOURCE_TYPES=["skills","prompts","themes"],FILE_PATTERNS={skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath3(p){return p.split(sep9).join("/")}function prefixIgnorePattern2(line,prefix){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative6(rootDir,dir),prefix=relativeDir?`${toPosixPath3(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join39(dir,filename);if(existsSync14(ignorePath))try{let patterns=readFileSync14(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve13(root,match2)).filter(path15=>relative6(root,path15).split(sep9).every(segment2=>segment2===".."||!segment2.startsWith("."))).sort((a,b2)=>a<b2?-1:a>b2?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync14(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync12(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync14(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!ig.ignores(relPath)&&(mode==="project"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}isDir&&(ig.ignores(`${relPath}/`)||entries.push(...collectSkillEntries(fullPath,mode,ig,root)))}}catch{}return entries}function collectAutoSkillEntries(dir,mode){return collectSkillEntries(dir,mode)}function findGitRepoRoot(startDir){let dir=resolve13(startDir);for(;;){if(existsSync14(join39(dir,".git")))return dir;let parent=dirname21(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve13(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join39(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname21(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function collectResourceFiles(dir,resourceType){return resourceType==="skills"?collectSkillEntries(dir,"project"):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentName=isSkillFile?basename11(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath3(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath3(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var import_semver3=__toESM(require_semver2(),1);import{homedir as homedir7}from"node:os";import{join as join40,relative as relative7}from"node:path";var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path15="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path15=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path15=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path15=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path15,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}function isExactNpmVersion(version){return(0,import_semver3.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver3.validRange)(version)??void 0:void 0}function getHomeDir(){return process.env.HOME||homedir7()}function getBaseDirForScope(ctx,scope){return scope==="project"?join40(ctx.cwd,CONFIG_DIR_NAME):scope==="user"?ctx.agentDir:ctx.cwd}function resolvePath3(ctx,input){return resolvePath(input,ctx.cwd,{homeDir:getHomeDir(),trim:!0})}function resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}function parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}function parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}function getPackageSourceString(pkg2){return typeof pkg2=="string"?pkg2:pkg2.source}function getSourceMatchKeyForInput(ctx,source){let parsed=parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${resolvePath3(ctx,parsed.path)}`}function getSourceMatchKeyForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}function buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}function findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg2 of configuredPackages){let sourceStr=getPackageSourceString(pkg2),parsed=parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}function normalizePackageSourceForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type!=="local")return source;let baseDir=getBaseDirForScope(ctx,scope),resolved=resolvePath3(ctx,parsed.path);return relative7(baseDir,resolved)||"."}function getPackageIdentity(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}return`local:${resolvePath3(ctx,parsed.path)}`}function dedupePackages(ctx,packages){let result=[],seen=new Map;for(let entry of packages){let identity=getPackageIdentity(ctx,getPackageSourceString(entry.pkg),entry.scope),index3=seen.get(identity);if(index3===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index3];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index3]=entry)}return result}import{readFileSync as readFileSync15}from"node:fs";var RESOURCE_FIELDS=["skills","prompts","themes"];function isObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg2=JSON.parse(stripBom(readFileSync15(packageJsonPath,"utf-8")));if(!isObject4(pkg2)||!isObject4(pkg2.pi))return null;let manifest={};for(let field2 of RESOURCE_FIELDS){let entries=pkg2.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}function resourcePrecedenceRank(m2){return m2.origin==="package"?4:(m2.scope==="project"?0:2)+(m2.source==="local"?0:1)}function collectPackageResources(packageRoot,accumulator,filter2,metadata){if(filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=getTargetMap(accumulator,resourceType);filter2.autoload===!1?applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}let manifest=readPiManifest(join41(packageRoot,"package.json"));if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];addManifestEntries(entries,packageRoot,resourceType,getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}function collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries){addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(target,f,metadata,!0)}}function applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=collectManifestFiles(packageRoot,resourceType);if(userPatterns.length===0){for(let f of allFiles)addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);addResource(target,f,metadata,enabled)}}function applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=collectManifestFiles(packageRoot,resourceType),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)addResource(target,filePath,metadata,enabled)}function collectManifestFiles(packageRoot,resourceType){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=collectFilesFromManifestEntries(entries,packageRoot,resourceType),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join41(packageRoot,resourceType);if(!existsSync15(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType);return{allFiles,enabledByManifest:new Set(allFiles)}}function addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=collectFilesFromManifestEntries(entries,root,resourceType),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&addResource(target,f,metadata,!0)}function collectFilesFromManifestEntries(entries,root,resourceType){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve14(root,entry)]);return collectFilesFromPaths(resolved,resourceType)}function resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>resolvePathFromBase(p,baseDir)),allFiles=collectFilesFromPaths(resolvedPlain,resourceType),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)addResource(target,f,metadata,enabledPaths.has(f))}function addAutoDiscoveredResources(cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[]},projectOverrides={skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[]},userDirs={skills:join41(globalBaseDir,"skills"),prompts:join41(globalBaseDir,"prompts"),themes:join41(globalBaseDir,"themes")},projectDirs={skills:join41(projectBaseDir,"skills"),prompts:join41(projectBaseDir,"prompts"),themes:join41(projectBaseDir,"themes")},userAgentsSkillsDir=join41(getHomeDir(),".agents","skills"),projectAgentsSkillDirs=collectAncestorAgentsSkillDirs(cwd).filter(dir=>resolve14(dir)!==resolve14(userAgentsSkillsDir)),addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=getTargetMap(accumulator,resourceType);for(let path15 of paths){let enabled=isEnabledByOverrides(path15,overrides,baseDir);addResource(target,path15,metadata,enabled)}};addResources("skills",collectAutoSkillEntries(projectDirs.skills,"project"),projectMetadata,projectOverrides.skills,projectBaseDir);for(let agentsSkillsDir of projectAgentsSkillDirs){let agentsBaseDir=dirname22(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addResources("skills",collectAutoSkillEntries(agentsSkillsDir,"agents"),agentsMetadata,projectOverrides.skills,agentsBaseDir)}addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("skills",collectAutoSkillEntries(userDirs.skills,"project"),userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname22(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addResources("skills",collectAutoSkillEntries(userAgentsSkillsDir,"agents"),userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir)}function collectFilesFromPaths(paths,resourceType){let files=[];for(let p of paths)if(existsSync15(p))try{let stats=statSync12(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType))}catch{}return files}function getTargetMap(accumulator,resourceType){switch(resourceType){case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;default:throw new Error(`Unknown resource type: ${resourceType}`)}}function addResource(map,path15,metadata,enabled){path15&&(map.has(path15)||map.set(path15,{metadata,enabled}))}function createAccumulator(){return{skills:new Map,prompts:new Map,themes:new Map}}function toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path15,{metadata,enabled}])=>({path:path15,enabled,metadata}));resolved.sort((a,b2)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b2.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes)}}var NETWORK_TIMEOUT_MS2=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4,DefaultPackageManager=class{cwd;agentDir;settingsManager;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}get context(){return{cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path15=this.getNpmInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="git"){let path15=this.getGitInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path15=this.resolvePathFromBase(parsed.path,baseDir);return existsSync16(path15)?path15:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);throw this.emitProgress({type:"error",action,source,message:errorMessage2}),error2}}async resolve(onMissing){let accumulator=createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join42(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}return addAutoDiscoveredResources(this.cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),toResolvedPaths(accumulator)}async resolveSourceResources(sources,options){let accumulator=createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg2 of globalSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg2 of projectSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync16(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg2 of globalSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg2 of projectSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled2()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=getManagedNpmInstallPath(this.context,source,scope),installedVersion=existsSync16(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled2())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync16(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync16(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg:pkg2,scope}of sources){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source,filter2=typeof pkg2=="object"?pkg2:void 0,deltaBase=this.findAutoloadDeltaBase(pkg2,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope),resolvedLocal=this.resolvePathFromBase(parsed.path,baseDir);if(existsSync16(resolvedLocal))try{statSync13(resolvedLocal).isDirectory()&&(metadata.baseDir=resolvedLocal,collectPackageResources(resolvedLocal,accumulator,filter2,metadata))}catch{}continue}let installMissing=async()=>{if(isOfflineModeEnabled2())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync16(installedPath)||!await installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync16(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled2()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg2,scope,sources){if(scope!=="project"||typeof pkg2!="object"||pkg2.autoload!==!1)return;let identity=this.getPackageIdentity(pkg2.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}parseSource(source){return parseSource(source)}getBaseDirForScope(scope){return getBaseDirForScope(this.context,scope)}resolvePath(input){return resolvePath3(this.context,input)}resolvePathFromBase(input,baseDir){return resolvePathFromBase(input,baseDir)}getPackageSourceString(pkg2){return getPackageSourceString(pkg2)}getSourceMatchKeyForInput(source){return getSourceMatchKeyForInput(this.context,source)}getSourceMatchKeyForSettings(source,scope){return getSourceMatchKeyForSettings(this.context,source,scope)}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){return normalizePackageSourceForSettings(this.context,source,scope)}getPackageIdentity(source,scope){return getPackageIdentity(this.context,source,scope)}dedupePackages(packages){return dedupePackages(this.context,packages)}buildNoMatchingPackageMessage(source,configuredPackages){return buildNoMatchingPackageMessage(source,configuredPackages)}getNpmCommand(){return getNpmCommand(this.context)}getInstalledNpmVersion(installedPath){return getInstalledNpmVersion(installedPath)}getGitInstallPath(source,scope){return getGitInstallPath(this.context,source,scope)}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled2())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}catch{return!1}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver4.maxSatisfying)(versions,range2):[...versions].sort(import_semver4.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled2())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2,env:{GIT_TERMINAL_PROMPT:"0"}})}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(getPackageManagerName(this.context)==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join42(dirname23(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(getPackageManagerName(this.context)!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path15=entry.dependencies?.[packageName]?.path;if(path15)return path15}}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join42(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=getManagedNpmInstallPath(this.context,source,scope);if(scope!=="user"||existsSync16(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync16(legacyPath)?legacyPath:managedPath}async installNpm(source,scope,temporary){let installRoot=getNpmInstallRoot(this.context,scope,temporary);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,[source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);if(!existsSync16(installRoot))return;let packageManagerName=getPackageManagerName(this.context);if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync16(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=getGitInstallRoot(this.context,scope);gitRoot&&ensureGitIgnore(gitRoot),mkdirSync11(dirname23(targetDir),{recursive:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}catch(error2){throw rmSync4(targetDir,{recursive:!0,force:!0}),pruneEmptyGitParents(targetDir,gitRoot),error2}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync16(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}async repairMissingGitDependencies(targetDir){hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error2){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error2}let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir}),rmSync4(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),markerPath=getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync16(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync10(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled2())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync4(targetDir,{recursive:!0,force:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0}),pruneEmptyGitParents(targetDir,getGitInstallRoot(this.context,scope))}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}spawnCommand(command,args,options){let env2=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env:env2})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env2=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env:env2})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,child.kill()},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error2=>{timeout&&clearTimeout(timeout),reject2(error2)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject2(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject2(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject2),child.on("exit",code=>{code===0?resolvePromise():reject2(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env2=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:env2});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{randomUUID as randomUUID15}from"crypto";import{existsSync as existsSync17,mkdirSync as mkdirSync12,readFileSync as readFileSync16,writeFileSync as writeFileSync11}from"fs";import{dirname as dirname24,join as join43}from"path";function isMergeableObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function deepMergeObjects(base,overrides){let result={...base};for(let key of Object.keys(overrides)){let overrideValue=overrides[key];if(overrideValue===void 0)continue;let baseValue=base[key];result[key]=isMergeableObject(baseValue)&&isMergeableObject(overrideValue)?deepMergeObjects(baseValue,overrideValue):overrideValue}return result}function deepMergeSettings(base,overrides){return deepMergeObjects(base,overrides)}function parseTimeoutSetting(value,settingName){let timeoutMs=parseHttpIdleTimeoutMs(value);if(timeoutMs!==void 0)return timeoutMs;if(value!==void 0)throw new Error(`Invalid ${settingName} setting: ${String(value)}`)}function toSettingsError(scope,error2,path15){return{scope,...path15?{path:path15}:{},error:error2 instanceof Error?error2:new Error(String(error2))}}var FileSettingsStorage=class{globalSettingsPath;projectSettingsPath;constructor(cwd,agentDir){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir);this.globalSettingsPath=join43(resolvedAgentDir,"settings.json"),this.projectSettingsPath=join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")}acquireLockSyncWithRetry(path15){let lastError;for(let attempt2=1;attempt2<=10;attempt2++)try{return import_proper_lockfile2.default.lockSync(path15,{realpath:!1})}catch(error2){if((typeof error2=="object"&&error2!==null&&"code"in error2?String(error2.code):void 0)!=="ELOCKED"||attempt2===10)throw error2;lastError=error2;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire settings lock")}withLock(scope,fn){let path15=scope==="global"?this.globalSettingsPath:this.projectSettingsPath,dir=dirname24(path15),release;try{let fileExists2=existsSync17(path15);fileExists2&&(release=this.acquireLockSyncWithRetry(path15));let current=fileExists2?readFileSync16(path15,"utf-8"):void 0,next=fn(current);next!==void 0&&(existsSync17(dir)||mkdirSync12(dir,{recursive:!0}),release||(release=this.acquireLockSyncWithRetry(path15)),writeFileSync11(path15,next,"utf-8"))}finally{release&&release()}}},InMemorySettingsStorage=class{global;project;withLock(scope,fn){let current=scope==="global"?this.global:this.project,next=fn(current);next!==void 0&&(scope==="global"?this.global=next:this.project=next)}},SettingsManager=class _SettingsManager{storage;globalSettings;projectSettings;settings;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(storage,initialGlobal,initialProject,globalLoadError=null,projectLoadError=null,initialErrors=[],settingsPaths={}){this.storage=storage,this.globalSettings=initialGlobal,this.projectSettings=initialProject,this.globalSettingsLoadError=globalLoadError,this.projectSettingsLoadError=projectLoadError,this.errors=[...initialErrors],this.settingsPaths=settingsPaths,this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}static create(cwd,agentDir=getAgentDir(),options={}){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),storage=new FileSettingsStorage(resolvedCwd,resolvedAgentDir);return _SettingsManager.fromStorageWithPaths(storage,options,{global:join43(resolvedAgentDir,"settings.json"),project:join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")})}static fromStorage(storage,options={}){return _SettingsManager.fromStorageWithPaths(storage,options)}static fromStorageWithPaths(storage,options,settingsPaths={}){let globalLoad=_SettingsManager.tryLoadFromStorage(storage,"global"),projectLoad=_SettingsManager.tryLoadFromStorage(storage,"project"),initialErrors=[];return globalLoad.error&&initialErrors.push(toSettingsError("global",globalLoad.error,settingsPaths.global)),projectLoad.error&&initialErrors.push(toSettingsError("project",projectLoad.error,settingsPaths.project)),new _SettingsManager(storage,globalLoad.settings,projectLoad.settings,globalLoad.error,projectLoad.error,initialErrors,settingsPaths)}static inMemory(settings2={},options={}){let storage=new InMemorySettingsStorage,initialSettings=_SettingsManager.migrateSettings(structuredClone(settings2));return storage.withLock("global",()=>JSON.stringify(initialSettings,null,2)),_SettingsManager.fromStorage(storage,options)}static loadFromStorage(storage,scope){let content;if(storage.withLock(scope,current=>{content=current}),!content)return{};let settings2=JSON.parse(stripBom(content));return _SettingsManager.migrateSettings(settings2)}static tryLoadFromStorage(storage,scope){try{return{settings:_SettingsManager.loadFromStorage(storage,scope),error:null}}catch(error2){return{settings:{},error:error2}}}static migrateSettings(settings2){if("queueMode"in settings2&&!("steeringMode"in settings2)&&(settings2.steeringMode=settings2.queueMode,delete settings2.queueMode),!("transport"in settings2)&&typeof settings2.websockets=="boolean"&&(settings2.transport=settings2.websockets?"websocket":"sse",delete settings2.websockets),"skills"in settings2&&typeof settings2.skills=="object"&&settings2.skills!==null&&!Array.isArray(settings2.skills)){let skillsSettings=settings2.skills;skillsSettings.enableSkillCommands!==void 0&&settings2.enableSkillCommands===void 0&&(settings2.enableSkillCommands=skillsSettings.enableSkillCommands),Array.isArray(skillsSettings.customDirectories)&&skillsSettings.customDirectories.length>0?settings2.skills=skillsSettings.customDirectories:delete settings2.skills}if("retry"in settings2&&typeof settings2.retry=="object"&&settings2.retry!==null&&!Array.isArray(settings2.retry)){let retrySettings=settings2.retry,providerSettings=typeof retrySettings.provider=="object"&&retrySettings.provider!==null?retrySettings.provider:void 0;typeof retrySettings.maxDelayMs=="number"&&(providerSettings?.maxRetryDelayMs===void 0||providerSettings?.maxRetryDelayMs===null)&&(retrySettings.provider={...providerSettings??{},maxRetryDelayMs:retrySettings.maxDelayMs}),delete retrySettings.maxDelayMs}return settings2}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let globalLoad=_SettingsManager.tryLoadFromStorage(this.storage,"global");globalLoad.error?(this.globalSettingsLoadError=globalLoad.error,this.recordError("global",globalLoad.error)):(this.globalSettings=globalLoad.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project");projectLoad.error?(this.projectSettingsLoadError=projectLoad.error,this.recordError("project",projectLoad.error)):(this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=null),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}applyOverrides(overrides){this.settings=deepMergeSettings(this.settings,overrides)}markModified(field2,nestedKey){this.modifiedFields.add(field2),nestedKey&&(this.modifiedNestedFields.has(field2)||this.modifiedNestedFields.set(field2,new Set),this.modifiedNestedFields.get(field2).add(nestedKey))}markProjectModified(field2,nestedKey){this.modifiedProjectFields.add(field2),nestedKey&&(this.modifiedProjectNestedFields.has(field2)||this.modifiedProjectNestedFields.set(field2,new Set),this.modifiedProjectNestedFields.get(field2).add(nestedKey))}recordError(scope,error2){this.errors.push(toSettingsError(scope,error2,this.settingsPaths[scope]))}clearModifiedScope(scope){if(scope==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(scope,task){this.writeQueue=this.writeQueue.then(()=>{task(),this.clearModifiedScope(scope)}).catch(error2=>{this.recordError(scope,error2)})}cloneModifiedNestedFields(source){let snapshot2=new Map;for(let[key,value]of source.entries())snapshot2.set(key,new Set(value));return snapshot2}persistScopedSettings(scope,snapshotSettings,modifiedFields,modifiedNestedFields){this.storage.withLock(scope,current=>{let currentFileSettings=current?_SettingsManager.migrateSettings(JSON.parse(stripBom(current))):{},mergedSettings={...currentFileSettings};for(let field2 of modifiedFields){let value=snapshotSettings[field2];if(modifiedNestedFields.has(field2)&&typeof value=="object"&&value!==null){let nestedModified=modifiedNestedFields.get(field2),baseNested=currentFileSettings[field2]??{},inMemoryNested=value,mergedNested={...baseNested};for(let nestedKey of nestedModified)mergedNested[nestedKey]=inMemoryNested[nestedKey];mergedSettings[field2]=mergedNested}else mergedSettings[field2]=value}return JSON.stringify(mergedSettings,null,2)})}save(){if(this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let snapshotGlobalSettings=structuredClone(this.globalSettings),modifiedFields=new Set(this.modifiedFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",snapshotGlobalSettings,modifiedFields,modifiedNestedFields)})}saveProjectSettings(settings2){if(this.projectSettings=structuredClone(settings2),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let snapshotProjectSettings=structuredClone(this.projectSettings),modifiedFields=new Set(this.modifiedProjectFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",snapshotProjectSettings,modifiedFields,modifiedNestedFields)})}updateProjectSettings(field2,update){let projectSettings=structuredClone(this.projectSettings);update(projectSettings),this.markProjectModified(field2),this.saveProjectSettings(projectSettings)}async flush(){await this.writeQueue}drainErrors(){let drained=[...this.errors];return this.errors=[],drained}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(version){this.globalSettings.lastChangelogVersion=version,this.markModified("lastChangelogVersion"),this.save()}getSuiteNoticeAcknowledgement(suiteId){return this.settings.suiteNoticesAcknowledged?.[suiteId]}setSuiteNoticeAcknowledgement(suiteId,ack){let next={...this.globalSettings.suiteNoticesAcknowledged??{},...this.settings.suiteNoticesAcknowledged??{}},existing=next[suiteId];next[suiteId]={...typeof existing=="object"&&existing!==null?existing:{},...ack.driftDigest===void 0?{}:{driftDigest:ack.driftDigest},...ack.upgradeRevision===void 0?{}:{upgradeRevision:ack.upgradeRevision}},this.globalSettings.suiteNoticesAcknowledged=next,this.settings.suiteNoticesAcknowledged=next,this.markModified("suiteNoticesAcknowledged"),this.save()}getSessionDir(){let sessionDir=this.settings.sessionDir;return sessionDir&&normalizePath(sessionDir)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}getMemoryModeSetting(){return this.settings.memory?.mode}setDefaultProvider(provider){this.globalSettings.defaultProvider=provider,this.markModified("defaultProvider"),this.save()}setDefaultModel(modelId){this.globalSettings.defaultModel=modelId,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(provider,modelId){this.globalSettings.defaultProvider=provider,this.globalSettings.defaultModel=modelId,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(mode){this.globalSettings.steeringMode=mode,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(mode){this.globalSettings.followUpMode=mode,this.markModified("followUpMode"),this.save()}getThemeSetting(){let value=this.settings.theme;if(typeof value=="string")return value}getTheme(){let theme2=this.getThemeSetting();return theme2?.includes("/")?void 0:theme2}setTheme(theme2){this.globalSettings.theme=theme2,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(level){this.globalSettings.defaultThinkingLevel=level,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(provider,modelId){return this.settings.modelThinkingLevels?.[`${provider}/${modelId}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(provider,modelId,level){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`]=level,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(provider,modelId){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(transport){this.globalSettings.transport=transport,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(enabled){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=enabled,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(enabled){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=enabled,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??5,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS}}getHttpIdleTimeoutMs(){return parseTimeoutSetting(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??DEFAULT_HTTP_IDLE_TIMEOUT_MS}setHttpIdleTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs)||timeoutMs<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(timeoutMs),this.markModified("httpIdleTimeoutMs"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){let configuredEditor=this.settings.externalEditor;if(typeof configuredEditor=="string"&&configuredEditor.trim()!=="")return configuredEditor;let environmentEditor=process.env.VISUAL||process.env.EDITOR;return environmentEditor||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(hide){this.globalSettings.hideThinkingBlock=hide,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(show){this.globalSettings.showCacheMissNotices=show,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){let shellPath=this.settings.shellPath;return shellPath&&normalizePath(shellPath)}setShellPath(path15){this.globalSettings.shellPath=path15,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(quiet){this.globalSettings.quietStartup=quiet,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(prefix){this.globalSettings.shellCommandPrefix=prefix,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(command){this.globalSettings.npmCommand=command?[...command]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(collapse){this.globalSettings.collapseChangelog=collapse,this.markModified("collapseChangelog"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(enabled){this.globalSettings.enableAnalytics=enabled,this.markModified("enableAnalytics"),enabled&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=randomUUID15(),this.markModified("trackingId")),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(packages){this.globalSettings.packages=packages,this.markModified("packages"),this.save()}setProjectPackages(packages){this.updateProjectSettings("packages",settings2=>{settings2.packages=packages})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(paths){this.globalSettings.skills=paths,this.markModified("skills"),this.save()}setProjectSkillPaths(paths){this.updateProjectSettings("skills",settings2=>{settings2.skills=paths})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(paths){this.globalSettings.prompts=paths,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(paths){this.updateProjectSettings("prompts",settings2=>{settings2.prompts=paths})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(paths){this.globalSettings.themes=paths,this.markModified("themes"),this.save()}setProjectThemePaths(paths){this.updateProjectSettings("themes",settings2=>{settings2.themes=paths})}setProjectSuite(id){this.updateProjectSettings("suite",settings2=>{if(id===void 0){delete settings2.suite;return}settings2.suite=id})}setSuite(id){id===void 0?delete this.globalSettings.suite:this.globalSettings.suite=id,this.markModified("suite"),this.save()}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(enabled){this.globalSettings.enableSkillCommands=enabled,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){let terminal=this.settings.terminal,images=terminal?.images;return{...images==="kitty"||images==="iterm2"?{images}:images===!1?{images:null}:{},...typeof terminal?.trueColor=="boolean"?{trueColor:terminal.trueColor}:{},...typeof terminal?.hyperlinks=="boolean"?{hyperlinks:terminal.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(show){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=show,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let width=this.settings.terminal?.imageWidthCells;return typeof width!="number"||!Number.isFinite(width)?60:Math.max(1,Math.floor(width))}setImageWidthCells(width){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(width)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){if(this.settings.terminal?.clearOnShrink!==void 0)return this.settings.terminal.clearOnShrink;let configuredValue=process.env.AGENT_FORGE_CLEAR_ON_SHRINK;return configuredValue===void 0?process.env.PI_CLEAR_ON_SHRINK==="1":configuredValue==="1"}setClearOnShrink(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=enabled,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=enabled,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":"regular"}setTuiMode(mode){this.globalSettings.tuiMode=mode,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(output){this.globalSettings.fullscreenExitOutput=output,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){let mode=this.settings.fullscreenScrollbar;return mode==="always"||mode==="hidden"?mode:"auto"}setFullscreenScrollbar(mode){this.globalSettings.fullscreenScrollbar=mode,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(enabled){this.globalSettings.fullscreenCopyOnSelect=enabled,this.markModified("fullscreenCopyOnSelect"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(enabled){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=enabled,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(blocked){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=blocked,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){let tools=this.settings.defaultTools;return tools?[...tools]:void 0}setEnabledModels(patterns){this.globalSettings.enabledModels=patterns,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(action){this.globalSettings.doubleEscapeAction=action,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let mode=this.settings.treeFilterMode;return mode&&["default","no-tools","user-only","labeled-only","all"].includes(mode)?mode:"default"}setTreeFilterMode(mode){this.globalSettings.treeFilterMode=mode,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){if(this.settings.showHardwareCursor!==void 0)return this.settings.showHardwareCursor;let configuredValue=process.env.AGENT_FORGE_HARDWARE_CURSOR;return configuredValue===void 0?process.env.PI_HARDWARE_CURSOR==="1":configuredValue==="1"}setShowHardwareCursor(enabled){this.globalSettings.showHardwareCursor=enabled,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(padding){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(padding))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===0?0:1}setOutputPad(padding){this.globalSettings.outputPad=padding,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(maxVisible){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(maxVisible))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){let mode=this.settings.markdown?.mermaid;return mode==="off"||mode==="final"?mode:"streaming"}setMermaidRenderingMode(mode){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=mode,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(warnings){this.globalSettings.warnings={...warnings},this.markModified("warnings"),this.save()}};import{existsSync as existsSync19,readdirSync as readdirSync13,readFileSync as readFileSync18,statSync as statSync15}from"node:fs";import{basename as basename12,dirname as dirname26,join as join45,resolve as resolve16,sep as sep10}from"node:path";import{execFile,spawnSync as spawnSync4}from"child_process";import{existsSync as existsSync18,readFileSync as readFileSync17,statSync as statSync14,unwatchFile,watchFile}from"fs";import{dirname as dirname25,join as join44,resolve as resolve15}from"path";function findGitPaths(cwd){let dir=cwd;for(;;){let gitPath=join44(dir,".git");if(existsSync18(gitPath))try{let stat5=statSync14(gitPath);if(stat5.isFile()){let content=readFileSync17(gitPath,"utf8").trim();if(content.startsWith("gitdir: ")){let gitDir=resolve15(dir,content.slice(8).trim()),headPath=join44(gitDir,"HEAD");if(!existsSync18(headPath))return null;let commonDirPath=join44(gitDir,"commondir"),commonGitDir=existsSync18(commonDirPath)?resolve15(gitDir,readFileSync17(commonDirPath,"utf8").trim()):gitDir;return{repoDir:dir,commonGitDir,headPath}}}else if(stat5.isDirectory()){let headPath=join44(gitPath,"HEAD");return existsSync18(headPath)?{repoDir:dir,commonGitDir:gitPath,headPath}:null}}catch{return null}let parent=dirname25(dir);if(parent===dir)return null;dir=parent}}function resolveBranchWithGitSync(repoDir){let result=spawnSync4("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return(result.status===0?result.stdout.trim():"")||null}function resolveBranchWithGitAsync(repoDir){return new Promise(resolvePromise=>{execFile("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8"},(error2,stdout)=>{if(error2){resolvePromise(null);return}let branch=stdout.trim();resolvePromise(branch||null)})})}function isWslEnvironment(){return process.platform==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)}function isWindowsMountedRepoPath(repoDir){return/^\/mnt\/[a-z](?:\/|$)/i.test(repoDir)}function shouldPollGitHead(repoDir){return isWslEnvironment()&&isWindowsMountedRepoPath(repoDir)}var FooterDataProvider=class _FooterDataProvider{cwd;static WATCH_DEBOUNCE_MS=500;cachedBranch=void 0;gitPaths=void 0;headWatcher=null;headWatchFilePath=null;headWatchFileListener=null;reftableWatcher=null;reftableTablesListWatcher=null;reftableTablesListPath=null;branchChangeCallbacks=new Set;availableProviderCount=0;refreshTimer=null;gitWatcherRetryTimer=null;refreshInFlight=!1;refreshPending=!1;disposed=!1;constructor(cwd){this.cwd=cwd,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher()}getGitBranch(){return this.cachedBranch===void 0&&(this.cachedBranch=this.resolveGitBranchSync()),this.cachedBranch}onBranchChange(callback){return this.branchChangeCallbacks.add(callback),()=>this.branchChangeCallbacks.delete(callback)}getAvailableProviderCount(){return this.availableProviderCount}setAvailableProviderCount(count){this.availableProviderCount=count}setCwd(cwd){this.cwd!==cwd&&(this.cwd=cwd,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.cachedBranch=void 0,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher(),this.notifyBranchChange())}dispose(){this.disposed=!0,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.branchChangeCallbacks.clear()}notifyBranchChange(){for(let cb of this.branchChangeCallbacks)cb()}scheduleRefresh(){if(!(this.disposed||this.refreshTimer)){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshGitBranchAsync()},_FooterDataProvider.WATCH_DEBOUNCE_MS)}}async refreshGitBranchAsync(){if(!this.disposed){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshInFlight=!0;try{let nextBranch=await this.resolveGitBranchAsync();if(this.disposed)return;if(this.cachedBranch!==void 0&&this.cachedBranch!==nextBranch){this.cachedBranch=nextBranch,this.notifyBranchChange();return}this.cachedBranch=nextBranch}finally{this.refreshInFlight=!1,this.refreshPending&&!this.disposed&&(this.refreshPending=!1,this.scheduleRefresh())}}}resolveGitBranchSync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?resolveBranchWithGitSync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}async resolveGitBranchAsync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?await resolveBranchWithGitAsync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}clearGitWatchers(){closeWatcher(this.headWatcher),this.headWatcher=null,this.headWatchFilePath&&this.headWatchFileListener&&(unwatchFile(this.headWatchFilePath,this.headWatchFileListener),this.headWatchFilePath=null,this.headWatchFileListener=null),closeWatcher(this.reftableWatcher),this.reftableWatcher=null,closeWatcher(this.reftableTablesListWatcher),this.reftableTablesListWatcher=null,this.reftableTablesListPath&&(unwatchFile(this.reftableTablesListPath),this.reftableTablesListPath=null),this.gitWatcherRetryTimer&&(clearTimeout(this.gitWatcherRetryTimer),this.gitWatcherRetryTimer=null)}scheduleGitWatcherRetry(){this.disposed||this.gitWatcherRetryTimer||(this.gitWatcherRetryTimer=setTimeout(()=>{this.gitWatcherRetryTimer=null,this.setupGitWatcher()},FS_WATCH_RETRY_DELAY_MS))}handleGitWatcherError(){this.clearGitWatchers(),this.scheduleGitWatcherRetry()}setupGitWatcher(){if(this.clearGitWatchers(),!this.gitPaths)return;let pollGitHead=shouldPollGitHead(this.gitPaths.repoDir);if(this.headWatcher=watchWithErrorHandler(dirname25(this.gitPaths.headPath),(_eventType,filename)=>{(!filename||filename==="HEAD")&&this.scheduleRefresh()},()=>this.handleGitWatcherError()),pollGitHead&&(this.headWatchFilePath=this.gitPaths.headPath,this.headWatchFileListener=(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()},watchFile(this.headWatchFilePath,{interval:1e3},this.headWatchFileListener)),!this.headWatcher&&!pollGitHead)return;let reftableDir=join44(this.gitPaths.commonGitDir,"reftable");if(existsSync18(reftableDir)){if(this.reftableWatcher=watchWithErrorHandler(reftableDir,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableWatcher)return;let tablesListPath=join44(reftableDir,"tables.list");if(existsSync18(tablesListPath)){if(this.reftableTablesListPath=tablesListPath,this.reftableTablesListWatcher=watchWithErrorHandler(tablesListPath,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableTablesListWatcher)return;watchFile(tablesListPath,{interval:250},(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()})}}}};function resolvePromptInput(input,description){if(input){if(existsSync19(input))try{return stripBom(readFileSync18(input,"utf-8"))}catch(error2){return console.error(source_default.yellow(`Warning: Could not read ${description} file ${input}: ${error2}`)),input}return input}}function loadContextFileFromDir(dir){let candidates=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(let filename of candidates){let filePath=join45(dir,filename);if(existsSync19(filePath))try{if(!statSync15(filePath).isFile())continue;return{path:filePath,content:stripBom(readFileSync18(filePath,"utf-8"))}}catch(error2){console.error(source_default.yellow(`Warning: Could not read ${filePath}: ${error2}`))}}return null}function findShadowedContextFile(cwd){let gitPaths=findGitPaths(cwd);if(!gitPaths)return;let commonGitDir=canonicalizePath(gitPaths.commonGitDir),worktreeRoot=canonicalizePath(gitPaths.repoDir),mainRepoRoot=dirname26(commonGitDir);if(!worktreeRoot.startsWith(`${mainRepoRoot}${sep10}`)||canonicalizePath(join45(mainRepoRoot,".git"))!==commonGitDir)return;let worktreeContextFile=loadContextFileFromDir(worktreeRoot);return worktreeContextFile?join45(mainRepoRoot,basename12(worktreeContextFile.path)):void 0}function loadProjectContextFiles(options){let resolvedCwd=resolvePath(options.cwd),resolvedAgentDir=resolvePath(options.agentDir),contextFiles=[],seenPaths=new Set,globalContext=loadContextFileFromDir(resolvedAgentDir);globalContext&&(contextFiles.push(globalContext),seenPaths.add(globalContext.path));let ancestorContextFiles=[],shadowedContextFile=findShadowedContextFile(resolvedCwd),currentDir=resolvedCwd;for(;;){let contextFile=loadContextFileFromDir(currentDir),isShadowed=shadowedContextFile!==void 0&&canonicalizePath(contextFile?.path??"")===shadowedContextFile;contextFile&&!isShadowed&&!seenPaths.has(contextFile.path)&&(ancestorContextFiles.unshift(contextFile),seenPaths.add(contextFile.path));let parentDir=dirname26(currentDir);if(parentDir===currentDir)break;currentDir=parentDir}return contextFiles.push(...ancestorContextFiles),contextFiles}var DefaultResourceLoader=class{cwd;agentDir;settingsManager;packageManager;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager??SettingsManager.create(this.cwd,this.agentDir),this.packageManager=new DefaultPackageManager({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}),this.additionalSkillPaths=options.additionalSkillPaths??[],this.additionalPromptTemplatePaths=options.additionalPromptTemplatePaths??[],this.additionalThemePaths=options.additionalThemePaths??[],this.noSkills=options.noSkills??!1,this.noPromptTemplates=options.noPromptTemplates??!1,this.noThemes=options.noThemes??!1,this.noContextFiles=options.noContextFiles??!1,this.systemPromptSource=options.systemPrompt,this.appendSystemPromptSource=options.appendSystemPrompt,this.skillsOverride=options.skillsOverride,this.promptsOverride=options.promptsOverride,this.themesOverride=options.themesOverride,this.agentsFilesOverride=options.agentsFilesOverride,this.systemPromptOverride=options.systemPromptOverride,this.appendSystemPromptOverride=options.appendSystemPromptOverride,this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[]}getSkills(){return{skills:this.skills.slice(),diagnostics:this.skillDiagnostics.slice()}}getPrompts(){return{prompts:this.prompts.slice(),diagnostics:this.promptDiagnostics.slice()}}getThemes(){return{themes:this.themes.slice(),diagnostics:this.themeDiagnostics.slice()}}getAgentsFiles(){return{agentsFiles:this.agentsFiles.slice()}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(path15=>({path:path15}))}extendResources(paths){let skillPaths=this.normalizeExtensionPaths(paths.skillPaths??[]),promptPaths=this.normalizeExtensionPaths(paths.promptPaths??[]),themePaths=this.normalizeExtensionPaths(paths.themePaths??[]);for(let entry of skillPaths)this.extensionSkillSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of promptPaths)this.extensionPromptSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of themePaths)this.extensionThemeSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));skillPaths.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,skillPaths.map(entry=>entry.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),promptPaths.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,promptPaths.map(entry=>entry.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),themePaths.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,themePaths.map(entry=>entry.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async reload(_options){await this.settingsManager.reload();let resolvedPaths=await this.packageManager.resolve();this.resourceMetadataByPath=new Map;let metadataByPath=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;let getEnabledResources=resources=>{for(let r of resources)metadataByPath.has(r.path)||metadataByPath.set(r.path,r.metadata);return resources.filter(r=>r.enabled)},getEnabledPaths=resources=>getEnabledResources(resources).map(r=>r.path),enabledSkillResources=getEnabledResources(resolvedPaths.skills),enabledPrompts=getEnabledPaths(resolvedPaths.prompts),enabledThemes=getEnabledPaths(resolvedPaths.themes),enabledSkills=enabledSkillResources.map(resource=>this.mapSkillPath(resource,metadataByPath)),skillPaths=this.noSkills?[...this.additionalSkillPaths]:this.mergePaths(enabledSkills,this.additionalSkillPaths);this.lastSkillPaths=skillPaths,this.updateSkillsFromPaths(skillPaths,metadataByPath);for(let p of this.additionalSkillPaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.skillDiagnostics.some(d2=>d2.path===resolved)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:resolved})}let promptPaths=this.noPromptTemplates?[...this.additionalPromptTemplatePaths]:this.mergePaths(enabledPrompts,this.additionalPromptTemplatePaths);this.lastPromptPaths=promptPaths,this.updatePromptsFromPaths(promptPaths,metadataByPath);for(let p of this.additionalPromptTemplatePaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.promptDiagnostics.some(d2=>d2.path===resolved)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:resolved})}let themePaths=this.noThemes?[...this.additionalThemePaths]:this.mergePaths(enabledThemes,this.additionalThemePaths);this.lastThemePaths=themePaths,this.updateThemesFromPaths(themePaths,metadataByPath);for(let p of this.additionalThemePaths){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.themeDiagnostics.some(d2=>d2.path===resolved)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:resolved})}let agentsFiles={agentsFiles:this.noContextFiles?[]:loadProjectContextFiles({cwd:this.cwd,agentDir:this.agentDir})},resolvedAgentsFiles=this.agentsFilesOverride?this.agentsFilesOverride(agentsFiles):agentsFiles;this.agentsFiles=resolvedAgentsFiles.agentsFiles;let systemPromptSource=this.systemPromptSource??this.discoverSystemPromptFile(),baseSystemPrompt=resolvePromptInput(systemPromptSource,"system prompt");this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(baseSystemPrompt):baseSystemPrompt,this.systemPromptSourcePath=systemPromptSource&&existsSync19(systemPromptSource)?resolvePath(systemPromptSource):void 0;let appendSources=this.appendSystemPromptSource;if(!appendSources){let discoveredAppendSystemPromptFile=this.discoverAppendSystemPromptFile();appendSources=discoveredAppendSystemPromptFile?[discoveredAppendSystemPromptFile]:[]}let baseAppend=appendSources.map(s=>resolvePromptInput(s,"append system prompt")).filter(s=>s!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(baseAppend):baseAppend,this.appendSystemPromptSourcePaths=appendSources.filter(source=>existsSync19(source)).map(source=>resolvePath(source))}mapSkillPath(resource,metadataByPath){if(resource.metadata.source!=="auto"&&resource.metadata.origin!=="package")return resource.path;try{if(!statSync15(resource.path).isDirectory())return resource.path}catch{return resource.path}let skillFile=join45(resource.path,"SKILL.md");return existsSync19(skillFile)?(metadataByPath.has(skillFile)||metadataByPath.set(skillFile,resource.metadata),skillFile):resource.path}normalizeExtensionPaths(entries){return entries.map(entry=>{let metadata=entry.metadata.baseDir?{...entry.metadata,baseDir:this.resolveResourcePath(entry.metadata.baseDir)}:entry.metadata;return{path:this.resolveResourcePath(entry.path),metadata}})}updateSkillsFromPaths(skillPaths,metadataByPath){let skillsResult;this.noSkills&&skillPaths.length===0?skillsResult={skills:[],diagnostics:[]}:skillsResult=loadSkills({cwd:this.cwd,agentDir:this.agentDir,skillPaths,includeDefaults:!1});let applySourceInfo=skill=>({...skill,sourceInfo:this.findSourceInfoForPath(skill.filePath,this.extensionSkillSourceInfos,metadataByPath)??skill.sourceInfo??this.getDefaultSourceInfoForPath(skill.filePath)});skillsResult={skills:skillsResult.skills.map(applySourceInfo),diagnostics:skillsResult.diagnostics};let resolvedSkills=this.skillsOverride?this.skillsOverride(skillsResult):skillsResult;this.skills=resolvedSkills.skills.map(applySourceInfo),this.skillDiagnostics=resolvedSkills.diagnostics}updatePromptsFromPaths(promptPaths,metadataByPath){let promptsResult;if(this.noPromptTemplates&&promptPaths.length===0)promptsResult={prompts:[],diagnostics:[]};else{let allPrompts=loadPromptTemplates({cwd:this.cwd,agentDir:this.agentDir,promptPaths,includeDefaults:!1});promptsResult=this.dedupePrompts(allPrompts)}let resolvedPrompts=this.promptsOverride?this.promptsOverride(promptsResult):promptsResult;this.prompts=resolvedPrompts.prompts.map(prompt=>({...prompt,sourceInfo:this.findSourceInfoForPath(prompt.filePath,this.extensionPromptSourceInfos,metadataByPath)??prompt.sourceInfo??this.getDefaultSourceInfoForPath(prompt.filePath)})),this.promptDiagnostics=resolvedPrompts.diagnostics}updateThemesFromPaths(themePaths,metadataByPath){let loadedThemes,themeDiagnostics;if(this.noThemes&&themePaths.length===0)loadedThemes=[],themeDiagnostics=[];else{let loaded=this.loadThemes(themePaths,!1),deduped=this.dedupeThemes(loaded.themes);loadedThemes=deduped.themes,themeDiagnostics=[...loaded.diagnostics,...deduped.diagnostics]}let themesResult={themes:loadedThemes.map(theme2=>this.buildThemeMeta(theme2,metadataByPath)),diagnostics:themeDiagnostics},resolvedThemes=this.themesOverride?this.themesOverride(themesResult):themesResult;this.themes=resolvedThemes.themes.map(meta=>this.buildThemeMeta(meta,metadataByPath)),this.themeDiagnostics=resolvedThemes.diagnostics}buildThemeMeta(source,metadataByPath){let sourcePath=source.sourcePath??"";return{name:source.name,sourcePath,sourceInfo:sourcePath?this.findSourceInfoForPath(sourcePath,this.extensionThemeSourceInfos,metadataByPath)??source.sourceInfo??this.getDefaultSourceInfoForPath(sourcePath):source.sourceInfo}}findSourceInfoForPath(resourcePath,extraSourceInfos,metadataByPath){if(!resourcePath)return;if(resourcePath.startsWith("<"))return this.getDefaultSourceInfoForPath(resourcePath);let normalizedResourcePath=resolve16(resourcePath);if(extraSourceInfos)for(let[sourcePath,sourceInfo]of extraSourceInfos.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return{...sourceInfo,path:resourcePath}}if(metadataByPath){let exact=metadataByPath.get(normalizedResourcePath)??metadataByPath.get(resourcePath);if(exact)return createSourceInfo(resourcePath,exact);for(let[sourcePath,metadata]of metadataByPath.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return createSourceInfo(resourcePath,metadata)}}}getDefaultSourceInfoForPath(filePath){if(filePath.startsWith("<")&&filePath.endsWith(">"))return{path:filePath,source:filePath.slice(1,-1).split(":")[0]||"temporary",scope:"temporary",origin:"top-level"};let normalizedPath=resolve16(filePath),agentRoots=[join45(this.agentDir,"skills"),join45(this.agentDir,"prompts"),join45(this.agentDir,"themes")],projectRoots=[join45(this.cwd,CONFIG_DIR_NAME,"skills"),join45(this.cwd,CONFIG_DIR_NAME,"prompts"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let root of agentRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"user",origin:"top-level",baseDir:root};for(let root of projectRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"project",origin:"top-level",baseDir:root};return{path:filePath,source:"local",scope:"temporary",origin:"top-level",baseDir:statSync15(normalizedPath).isDirectory()?normalizedPath:resolve16(normalizedPath,"..")}}mergePaths(primary,additional){let merged=[],seen=new Set;for(let p of[...primary,...additional]){let resolved=this.resolveResourcePath(p),canonicalPath=canonicalizePath(resolved);seen.has(canonicalPath)||(seen.add(canonicalPath),merged.push(resolved))}return merged}resolveResourcePath(p){return resolvePath(p,this.cwd,{trim:!0})}loadThemes(paths,includeDefaults=!0){let themes=[],diagnostics=[];if(includeDefaults){let defaultDirs=[join45(this.agentDir,"themes"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let dir of defaultDirs)this.loadThemesFromDir(dir,themes,diagnostics)}for(let p of paths){let resolved=this.resolveResourcePath(p);if(!existsSync19(resolved)){diagnostics.push({type:"warning",message:"theme path does not exist",path:resolved});continue}try{let stats=statSync15(resolved);stats.isDirectory()?this.loadThemesFromDir(resolved,themes,diagnostics):stats.isFile()&&resolved.endsWith(".json")?this.loadThemeFromFile(resolved,themes,diagnostics):diagnostics.push({type:"warning",message:"theme path is not a json file",path:resolved})}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme path";diagnostics.push({type:"warning",message,path:resolved})}}return{themes,diagnostics}}loadThemesFromDir(dir,themes,diagnostics){if(existsSync19(dir))try{let entries=readdirSync13(dir,{withFileTypes:!0});for(let entry of entries){let isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync15(join45(dir,entry.name)).isFile()}catch{continue}isFile&&entry.name.endsWith(".json")&&this.loadThemeFromFile(join45(dir,entry.name),themes,diagnostics)}}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme directory";diagnostics.push({type:"warning",message,path:dir})}}loadThemeFromFile(filePath,themes,diagnostics){try{themes.push(loadThemeFromPath(filePath))}catch(error2){let message=error2 instanceof Error?error2.message:"failed to load theme";diagnostics.push({type:"warning",message,path:filePath})}}dedupePrompts(prompts){let seen=new Map,diagnostics=[];for(let prompt of prompts){let existing=seen.get(prompt.name);existing?diagnostics.push({type:"collision",message:`name "/${prompt.name}" collision`,path:prompt.filePath,collision:{resourceType:"prompt",name:prompt.name,winnerPath:existing.filePath,loserPath:prompt.filePath}}):seen.set(prompt.name,prompt)}return{prompts:Array.from(seen.values()),diagnostics}}dedupeThemes(themes){let seen=new Map,diagnostics=[];for(let t of themes){let name=t.name??"unnamed",existing=seen.get(name);existing?diagnostics.push({type:"collision",message:`name "${name}" collision`,path:t.sourcePath,collision:{resourceType:"theme",name,winnerPath:existing.sourcePath??"<builtin>",loserPath:t.sourcePath??"<builtin>"}}):seen.set(name,t)}return{themes:Array.from(seen.values()),diagnostics}}discoverSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"SYSTEM.md");if(existsSync19(globalPath))return globalPath}discoverAppendSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"APPEND_SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"APPEND_SYSTEM.md");if(existsSync19(globalPath))return globalPath}isUnderPath(target,root){let normalizedRoot=resolve16(root);if(target===normalizedRoot)return!0;let prefix=normalizedRoot.endsWith(sep10)?normalizedRoot:`${normalizedRoot}${sep10}`;return target.startsWith(prefix)}};import{existsSync as existsSync23,mkdirSync as mkdirSync15,readFileSync as readFileSync20,writeFileSync as writeFileSync12}from"node:fs";import{isAbsolute as isAbsolute10,join as join50,relative as relative8,sep as sep11}from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{existsSync as existsSync22,realpathSync as realpathSync4}from"node:fs";import{readFile as readFile9}from"node:fs/promises";import{join as join49,resolve as resolve18}from"node:path";var import_semver5=__toESM(require_semver2(),1);var BUILTIN_CAPABILITY_PACKAGE_IDS=Object.freeze({"builtin.goal":"agent-forge.plugin.goal","builtin.plan":"agent-forge.plugin.plan","builtin.todo-set":"agent-forge.plugin.todo-set","builtin.session-share":"agent-forge.plugin.session-share","builtin.subagent-delegate":"agent-forge.plugin.subagent-delegate","builtin.memory":"agent-forge.plugin.memory"});import{constants as constants7,copyFileSync,existsSync as existsSync21,mkdirSync as mkdirSync13}from"node:fs";import{basename as basename13,join as join46,parse as parse4,resolve as resolve17}from"node:path";import{existsSync as existsSync20}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync20(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
|
|
1058
1058
|
Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
|
|
1059
1059
|
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
|
|
1060
1060
|
${issue.sessionCwd}
|
|
@@ -1064,8 +1064,8 @@ ${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{issue;const
|
|
|
1064
1064
|
`,1)[0]??"";return{header:parseHeader3(firstLine),bytes}}function readAgentSession(options){if(!isAgentSessionId2(options.sessionId))return;let dir=agentSessionsDir2(options.agentDir),filePath=findSessionFile2(dir,options.sessionId);if(filePath===void 0)return;let text,bytes;try{bytes=statSync16(filePath).size,text=readFileSync19(filePath,{encoding:"utf-8",flag:"r"})}catch{return}let maxBytes=options.maxBytes??DEFAULT_MAX_BYTES4,truncated=text.length>maxBytes,lines=(truncated?text.slice(0,maxBytes):text).split(`
|
|
1065
1065
|
`).filter(line=>line.trim()!==""),header=lines.length>0?parseHeader3(lines[0]):void 0,entries=[];for(let line of lines.slice(header===void 0?0:1))try{entries.push(JSON.parse(line))}catch{}let parentAgentSession=typeof header?.parentAgentSession=="string"?header.parentAgentSession:void 0,agentRole=typeof header?.agentRole=="string"?header.agentRole:void 0,cwd=typeof header?.cwd=="string"?header.cwd:void 0,createdAt=typeof header?.timestamp=="string"?header.timestamp:void 0;return{sessionId:options.sessionId,...parentAgentSession===void 0?{}:{parentAgentSession},...agentRole===void 0?{}:{agentRole},...cwd===void 0?{}:{cwd},...createdAt===void 0?{}:{createdAt},bytes,entryCount:entries.length,truncated,entries:Object.freeze(entries)}}function listAgentSessions(options){let names2,dir;try{dir=agentSessionsDir2(options.agentDir),names2=readdirSync14(dir).filter(name=>name.endsWith(".jsonl"))}catch{return Object.freeze([])}let summaries=[];for(let name of names2){let stem=name.slice(0,-6),separator=stem.lastIndexOf("_"),sessionId=separator===-1?stem:stem.slice(separator+1);if(!isAgentSessionId2(sessionId))continue;let filePath=join48(dir,name),scanned,modifiedAt;try{scanned=readHeader(filePath),modifiedAt=statSync16(filePath).mtimeMs}catch{continue}let parentAgentSession=typeof scanned.header?.parentAgentSession=="string"?scanned.header.parentAgentSession:void 0;if(options.parentAgentSession!==void 0&&parentAgentSession!==options.parentAgentSession)continue;let agentRole=typeof scanned.header?.agentRole=="string"?scanned.header.agentRole:void 0,createdAt=typeof scanned.header?.timestamp=="string"?scanned.header.timestamp:void 0;summaries.push({sessionId,...parentAgentSession===void 0?{}:{parentAgentSession},...agentRole===void 0?{}:{agentRole},...createdAt===void 0?{}:{createdAt},modifiedAt,bytes:scanned.bytes})}return summaries.sort((left,right)=>right.modifiedAt-left.modifiedAt),Object.freeze(summaries.slice(0,options.limit??DEFAULT_LIST_LIMIT))}function createCodingAgentFacade(session){return{version:1,prompt:(text,options)=>session.prompt(text,options),steer:(text,images,options)=>session.steer(text,images,options),abort:()=>session.abort(),waitForIdle:()=>session.waitForIdle(),compact:customInstructions=>session.compact(customInstructions),navigateTree:(targetId,options)=>session.navigateTree(targetId,options),reload:options=>session.reload(options),setModel:(model,options)=>session.setModel(model,options),setThinkingLevel:(level,options)=>session.setThinkingLevel(level,options),setActiveToolsByName:toolNames=>session.setActiveToolsByName(toolNames),getQueuedMessages:()=>({steering:session.getSteeringMessages(),followUp:session.getFollowUpMessages()}),clearQueue:()=>session.clearQueue(),recordSuiteMismatch:(originalSuiteId,currentSuiteId)=>session.recordSuiteMismatch(originalSuiteId,currentSuiteId),getSessionAPI:()=>session.getSessionAPI(),isIdle:()=>session.isIdle,getState:()=>session.state,getModel:()=>session.model,getToolNames:()=>session.getActiveToolNames(),getSessionId:()=>session.sessionId,getHeader:()=>session.sessionManager.getHeader(),subscribe:listener=>session.subscribe(listener),subscribeRawEventGate:listener=>session.agent.subscribe(()=>listener()),getSessionName:()=>session.sessionName,isCompacting:()=>session.isCompacting,isStreaming:()=>session.isStreaming,getContextUsage:()=>session.getContextUsage(),getSystemPrompt:()=>session.systemPrompt,getScopedModels:()=>session.scopedModels,getTree:()=>session.sessionManager.getTree(),getLeafId:()=>session.sessionManager.getLeafId(),getPromptTemplates:()=>session.promptTemplates,getToolDefinition:name=>session.getToolDefinition(name),getCwd:()=>session.sessionManager.getCwd(),getEntries:()=>session.sessionManager.getEntries(),getPendingMessageCount:()=>session.pendingMessageCount,followUp:(text,images,options)=>session.followUp(text,images,options),setScopedModels:scopedModels=>session.setScopedModels(scopedModels),cycleModel:(direction,options)=>session.cycleModel(direction,options),cycleThinkingLevel:options=>session.cycleThinkingLevel(options),setSteeringMode:mode=>session.setSteeringMode(mode),setFollowUpMode:mode=>session.setFollowUpMode(mode),setAutoCompactionEnabled:enabled=>session.setAutoCompactionEnabled(enabled),setSessionName:name=>session.setSessionName(name),abortBash:()=>session.abortBash(),abortCompaction:()=>session.abortCompaction(),abortRetry:()=>session.abortRetry(),abortBranchSummary:()=>session.abortBranchSummary(),captureBashEpoch:()=>session.captureBashEpoch(),isBashEpochCurrent:epoch=>session.isBashEpochCurrent(epoch),emitUserBash:excludeFromContext=>session.emitUserBash(excludeFromContext),executeBash:(command,onChunk,options)=>session.executeBash(command,onChunk,options),recordBashResult:(command,result,options)=>session.recordBashResult(command,result,options),getThinkingLevel:()=>session.thinkingLevel,getSteeringMode:()=>session.steeringMode,getFollowUpMode:()=>session.followUpMode,getSessionFile:()=>session.sessionFile,isAutoCompactionEnabled:()=>session.autoCompactionEnabled,getAvailableThinkingLevels:()=>session.getAvailableThinkingLevels(),getUserMessagesForForking:()=>session.getUserMessagesForForking(),getLastAssistantText:()=>session.getLastAssistantText(),getSessionStats:()=>session.getSessionStats(),setAutoRetryEnabled:enabled=>session.setAutoRetryEnabled(enabled),exportToHtml:(outputPath,options)=>session.exportToHtml(outputPath,options),appendLabelChange:(entryId,label)=>session.sessionManager.appendLabelChange(entryId,label),getSkills:()=>session.resourceLoader.getSkills(),getPrompts:()=>session.resourceLoader.getPrompts(),getThemes:()=>session.resourceLoader.getThemes(),getAgentsFiles:()=>session.resourceLoader.getAgentsFiles(),getSystemPromptSource:()=>session.resourceLoader.getSystemPromptSource(),getAppendSystemPromptSources:()=>session.resourceLoader.getAppendSystemPromptSources(),getSuiteId:()=>readSessionSuiteBinding(session.getSessionAPI().getBranchEntries())?.suiteId,getAvailableModels:()=>session.modelRuntime.getAvailableSnapshot(),isUsingSubscription:providerId=>session.modelRuntime.isUsingSubscription(providerId),getModelsError:()=>session.modelRuntime.getError(),getModelCatalog:()=>session.modelRuntime,checkProviderAuth:providerId=>session.modelRuntime.checkAuth(providerId),getProviderAuth:providerId=>session.modelRuntime.getAuth(providerId),getModelPriceSource:()=>session.modelRuntime,getModelAuthRuntime:()=>session.modelRuntime,getContextEntries:()=>session.sessionManager.buildContextEntries(),getSteeringMessages:()=>session.getSteeringMessages(),getFollowUpMessages:()=>session.getFollowUpMessages(),getRetryAttempt:()=>session.retryAttempt,isBashRunning:()=>session.isBashRunning,exportToJsonl:outputPath=>session.exportToJsonl(outputPath),dispose:()=>session.dispose()}}function createCodingAgentRuntimeFacade(runtime){let sessionManager=()=>runtime.session.sessionManager;return{version:1,newSession:(...args)=>runtime.newSession(...args),fork:(...args)=>runtime.fork(...args),switchSession:(...args)=>runtime.switchSession(...args),importFromJsonl:(...args)=>runtime.importFromJsonl(...args),dispose:()=>runtime.dispose(),setBeforeSessionInvalidate:beforeSessionInvalidate=>runtime.setBeforeSessionInvalidate(beforeSessionInvalidate),setRebindSession:rebindSession=>runtime.setRebindSession(rebindSession),getSessionFacade:()=>createCodingAgentFacade(runtime.session),listSessions:onProgress=>SessionManager.list(sessionManager().getCwd(),sessionManager().getSessionDir(),onProgress),listAllSessions:onProgress=>sessionManager().usesDefaultSessionDir()?SessionManager.listAll(onProgress):SessionManager.listAll(sessionManager().getSessionDir(),onProgress),getSessionFile:()=>sessionManager().getSessionFile(),getSessionDir:()=>sessionManager().getSessionDir(),usesDefaultSessionDir:()=>sessionManager().usesDefaultSessionDir(),isPersisted:()=>sessionManager().isPersisted(),getSessionId:()=>sessionManager().getSessionId()}}function areTimingsEnabled(){let configuredValue=process.env.AGENT_FORGE_TIMING;return configuredValue===void 0?process.env.PI_TIMING==="1":configuredValue==="1"}var ENABLED=areTimingsEnabled(),timingNamespaces=new Map;function resetTimings(namespace="main"){ENABLED&&timingNamespaces.set(namespace,{timings:[],lastTime:Date.now()})}function time(label,namespace="main"){if(!ENABLED)return;let now=Date.now();timingNamespaces.has(namespace)||resetTimings(namespace);let timingNamespace=timingNamespaces.get(namespace);timingNamespace.timings.push({label,ms:now-timingNamespace.lastTime}),timingNamespace.lastTime=now}function printTimingGroup(title,timings){let printableTimings=timings.filter(timing=>timing.ms>=0);if(printableTimings.length!==0){console.error(`
|
|
1066
1066
|
--- ${title} ---`);for(let t of printableTimings)console.error(` ${t.label}: ${t.ms}ms`);console.error(` TOTAL: ${printableTimings.reduce((a,b2)=>a+b2.ms,0)}ms`),console.error(`${"-".repeat(title.length+8)}
|
|
1067
|
-
`)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}setDefaultStreamFn(streamSimple);var AGENT_TASK_SETTLED_STATUSES=new Set(["queued","admitted","running","succeeded","failed","cancelled","timed_out","drain_timeout","runner_lost"]);function parseAgentTaskSettledDigestLine(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let record=parsed;if(!(typeof record.taskId!="string"||record.taskId==="")&&!(typeof record.sessionId!="string"||record.sessionId==="")&&!(typeof record.status!="string"||!AGENT_TASK_SETTLED_STATUSES.has(record.status))&&!(record.reasonCode!==void 0&&(typeof record.reasonCode!="string"||record.reasonCode==="")))return{taskId:record.taskId,taskSessionId:record.sessionId,status:record.status,...record.reasonCode===void 0?{}:{reasonCode:record.reasonCode}}}function deliverAgentTaskSettledDigestLine(session,line,hostLogger){let facts=parseAgentTaskSettledDigestLine(line);if(facts===void 0){hostLogger?.warn("sdk","background delegation settlement line is not a valid agent.task.settled source",{cause:line});return}session?.dispatchAgentTaskSettled(facts)}var OBSERVABILITY_PACKAGE_ID="agent-forge.plugin.observability",SUBAGENT_DELEGATE_PACKAGE_ID="agent-forge.plugin.subagent-delegate",MEMORY_PACKAGE_ID="agent-forge.plugin.memory",isMemoryModeV1=value=>value==="off"||value==="light"||value==="full";function resolveSdkMemoryMode(explicitMode,env2,settingsMode){if(explicitMode!==void 0)return isMemoryModeV1(explicitMode)?{mode:explicitMode}:{mode:"off",invalidEnvValue:explicitMode};let configured=env2.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();if(configured!==void 0&&configured!=="")return isMemoryModeV1(configured)?{mode:configured}:{mode:"off",invalidEnvValue:configured};let fromSettings=settingsMode?.trim().toLowerCase();if(fromSettings!==void 0&&fromSettings!=="")return isMemoryModeV1(fromSettings)?{mode:fromSettings}:{mode:"off",invalidSettingsValue:fromSettings};let legacy=env2.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();return legacy!==void 0&&legacy!==""?isMemoryModeV1(legacy)?{mode:legacy}:{mode:"off",invalidEnvValue:legacy}:{mode:"off"}}function getDefaultAgentDir(){return getAgentDir()}function injectAfterLastUserMessage(messages,injection){for(let index3=messages.length-1;index3>=0;index3-=1)if(messages[index3]?.role==="user")return[...messages.slice(0,index3+1),injection,...messages.slice(index3+1)];return messages}async function readCapabilityPluginManifestForOrdering(manifestPath){let raw;try{raw=JSON.parse(await readFile9(manifestPath,"utf8"))}catch(error2){throw new Error(`Failed to read capability plugin manifest ${manifestPath}: ${error2 instanceof Error?error2.message:String(error2)}`)}return parseCapabilityPluginManifest(raw,manifestPath)}async function createAgentSession(options={}){let cwd=resolvePath(options.cwd??options.sessionManager?.getCwd()??process.cwd()),agentDir=options.agentDir?resolvePath(options.agentDir):getDefaultAgentDir(),resourceLoader=options.resourceLoader,authPath=options.agentDir?join49(agentDir,"auth.json"):void 0,modelsPath=options.agentDir?join49(agentDir,"models.json"):void 0,modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath,modelsPath,credentials:options.credentials}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),suiteId=resolveSuiteId({explicit:options.suite,envSuite:process.env[SUITE_ENV_VAR],settings:settingsManager,agentDir}),suiteAssembly=createSuiteAssembly({cwd,agentDir,suiteId,pluginProfileId:options.pluginProfileId,selectedPluginIds:options.selectedPluginIds,disabledPluginIds:options.disabledPluginIds,pluginHost:options.pluginHost,verifiedPlugins:options.verifiedPlugins,manifestOverrides:options.manifestOverrides,pluginProfile:options.pluginProfile}),suiteWorkspace=suiteAssembly.workspace,resolvedAgentProfile=buildResolvedAgentProfileV1({suiteId,workspace:suiteWorkspace,...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile}}),capabilityWiring=options.suiteCapabilityWiring??!options.resourceLoader,capabilityDiagnostics=[],suitePreferenceDiagnostics=[],capabilitySkillsFilter,communicationMailbox,selfMailbox=()=>(communicationMailbox??=createSubagentMailbox({agentDir,ownerParentSessionId:()=>agentSessionRef.current?.sessionId}),communicationMailbox),communicationWiring=options.enableAgentTasks===!1&&options.subagentCommunicationWiring===void 0?void 0:{drainEscalations:sessionId=>selfMailbox().drainEscalations(sessionId),...options.subagentCommunicationWiring??{}},backgroundDigest={pending:[]},settingsMemoryMode=settingsManager.getMemoryModeSetting(),memoryModeOption=options.memoryCapability?.mode,memoryModeResolution=resolveSdkMemoryMode(memoryModeOption,process.env,settingsMemoryMode);if(capabilityWiring){let resolved=resolveBuiltinCapabilities(suiteWorkspace.suite.capabilities);for(let shortId of resolved.unknownShortIds)capabilityDiagnostics.push(suiteDanglingAssociationDiagnostic(suiteId,"capabilities",shortId));suiteWorkspace.suite.capabilities.includes("builtin.memory")&&(memoryModeResolution.invalidEnvValue!==void 0&&capabilityDiagnostics.push(`invalid AGENT_FORGE_MEMORY_MODE value "${memoryModeResolution.invalidEnvValue}"; memory stays off (fail-closed)`),memoryModeResolution.invalidSettingsValue!==void 0&&capabilityDiagnostics.push(`invalid memory.mode setting "${memoryModeResolution.invalidSettingsValue}"; memory stays off (fail-closed)`),memoryModeResolution.mode==="off"&&capabilityDiagnostics.push("memory disabled (mode=off) \u2014 set memory.mode (light|full) in settings.json to enable"));let suiteDefinition=suiteWorkspace.suite,suiteLocalSkillsDir=suiteAssembly.localSkillsDir;capabilitySkillsFilter=skills=>filterSuiteSkills(suiteDefinition,skills,{localSkillsDir:suiteLocalSkillsDir}).kept}let sessionManager=options.sessionManager??SessionManager.create(cwd,getDefaultSessionDir(cwd,agentDir)),hostLogger=options.hostLogger,traceOptions=options.traceOptions,observabilityCapture={},observabilityLogMirror={},observabilityGetMetrics={},traceService;options.traceEnabled!==!1&&(traceService={adapter:{getTraceFilePath:()=>{let sessionFilePath=sessionManager.getSessionFile();return sessionFilePath===void 0?null:getTraceFilePathForSession(sessionFilePath)},captureProviderPayload:(payload2,model2)=>{observabilityCapture.current?.(payload2,model2)},onSinkFailure:error2=>{hostLogger?.error("observability","trace sink failure",{cause:error2})},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId(),getParentAgentSessionId:()=>sessionManager.getHeader()?.parentAgentSession,getParentTraceId:()=>sessionManager.getHeader()?.parentTraceId,registerFacade:facade=>{observabilityCapture.current=facade?.captureProviderPayload,observabilityLogMirror.current=facade?.mirrorPluginLog,observabilityGetMetrics.current=facade?.getMetrics}},...traceOptions===void 0?{}:{options:traceOptions}}),resourceLoader||(resourceLoader=new DefaultResourceLoader({cwd,agentDir,settingsManager,...suiteAssembly.loaderOverrides,...suiteAssembly.localSkillsDir===void 0?{}:{additionalSkillPaths:[suiteAssembly.localSkillsDir]}}),await resourceLoader.reload(),time("resourceLoader.reload"));let existingSession=sessionManager.buildSessionContext(),hasExistingSession=existingSession.messages.length>0,branchEntries=sessionManager.getBranch(),sessionSuiteBinding=readSessionSuiteBinding(branchEntries),hasConversation=branchEntries.some(entry=>entry.type==="message"&&entry.message?.role==="user");if(hasConversation&&sessionSuiteBinding!==void 0){if(sessionSuiteBinding.suiteId!==suiteId)throw new SuiteRebindError(`Session is bound to suite "${sessionSuiteBinding.suiteId}" and cannot resume with "${suiteId}"; create a new session or migrate explicitly`);if(sessionSuiteBinding.profileIdentity!==void 0&&!profileIdentitiesCompatible(sessionSuiteBinding.profileIdentity,suiteWorkspace.identity))throw new SuiteRebindError("Session Profile identity drift detected; create a new session or migrate explicitly before reloading plugins")}let hasThinkingEntry=sessionManager.getBranch().some(entry=>entry.type==="thinking_level_change"),model=options.model,modelFallbackMessage;if(!model&&hasExistingSession&&existingSession.model){let restoredModel=modelRuntime.getModel(existingSession.model.provider,existingSession.model.modelId);restoredModel&&modelRuntime.hasConfiguredAuth(restoredModel.provider)&&(model=restoredModel),model||(modelFallbackMessage=`Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`)}let suiteModelPreference=suiteWorkspace.suite.model;if(!model&&suiteModelPreference!==null){let suiteModel=findExactModelReferenceMatch(suiteModelPreference,[...modelRuntime.getModels()]);suiteModel&&modelRuntime.hasConfiguredAuth(suiteModel.provider)?model=suiteModel:suitePreferenceDiagnostics.push(`Suite "${suiteId}" model "${suiteModelPreference}" does not resolve to an authenticated model; using the normal model resolution instead.`)}model||(model=(await findInitialModel({scopedModels:[],isContinuing:hasExistingSession,defaultProvider:settingsManager.getDefaultProvider(),defaultModelId:settingsManager.getDefaultModel(),defaultThinkingLevel:settingsManager.getDefaultThinkingLevel(),modelThinkingLevels:settingsManager.getAllModelThinkingLevels(),modelRuntime})).model,model?modelFallbackMessage&&(modelFallbackMessage+=`. Using ${model.provider}/${model.id}`):modelFallbackMessage=formatNoModelsAvailableMessage());let thinkingLevel=options.thinkingLevel;thinkingLevel===void 0&&hasExistingSession&&hasThinkingEntry&&(thinkingLevel=existingSession.thinkingLevel);let suiteThinkingPreference=suiteWorkspace.suite.thinking;if(thinkingLevel===void 0&&suiteThinkingPreference!==null&&(isValidThinkingLevel(suiteThinkingPreference)?thinkingLevel=suiteThinkingPreference:suitePreferenceDiagnostics.push(`Suite "${suiteId}" thinking "${suiteThinkingPreference}" is not a valid thinking level; using the normal thinking resolution instead.`)),thinkingLevel===void 0&&hasExistingSession&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),thinkingLevel===void 0&&model){let perModel=settingsManager.getModelThinkingLevel(model.provider,model.id);perModel&&(thinkingLevel=perModel)}thinkingLevel===void 0&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),model?thinkingLevel=clampThinkingLevel(model,thinkingLevel):thinkingLevel="off";let defaultActiveToolNames=options.capabilityMode==="readonly"?["read","grep","find","ls"]:["read","bash","edit","write"],configuredDefaultToolNames=settingsManager.getDefaultTools(),allowedToolNames=options.tools??(options.noTools==="all"?[]:void 0),excludedToolNames=options.excludeTools,excludedToolNameSet=excludedToolNames?new Set(excludedToolNames):void 0,initialActiveToolNames=((options.tools===void 0&&options.noTools===void 0&&options.capabilityMode!=="readonly"?[...suiteWorkspace.suite.tools]:void 0)??options.tools??(options.noTools?[]:configuredDefaultToolNames??defaultActiveToolNames)).filter(name=>!excludedToolNameSet?.has(name)),agent,convertToLlmWithBlockImages=messages=>{let converted=convertToLlm2(messages);return settingsManager.getBlockImages()?converted.map(msg=>{if(msg.role==="user"||msg.role==="toolResult"){let content=msg.content;if(Array.isArray(content)&&content.some(c2=>c2.type==="image")){let filteredContent=content.map(c2=>c2.type==="image"?{type:"text",text:"Image reading is disabled."}:c2).filter((c2,i,arr)=>!(c2.type==="text"&&c2.text==="Image reading is disabled."&&i>0&&arr[i-1].type==="text"&&arr[i-1].text==="Image reading is disabled."));return{...msg,content:filteredContent}}}return msg}):converted},agentSessionRef={},customStreamFn=options.streamFn;agent=new Agent({initialState:{systemPrompt:"",model,thinkingLevel,tools:[]},convertToLlm:convertToLlmWithBlockImages,streamFn:customStreamFn?(model2,context,streamOptions)=>customStreamFn(model2,context,streamOptions):async(model2,context,options2)=>{let providerRetrySettings=settingsManager.getProviderRetrySettings(),httpIdleTimeoutMs=settingsManager.getHttpIdleTimeoutMs(),effectiveTimeoutMs=httpIdleTimeoutMs===0?2147483647:httpIdleTimeoutMs,timeoutMs=options2?.timeoutMs??providerRetrySettings.timeoutMs??effectiveTimeoutMs,websocketConnectTimeoutMs=options2?.websocketConnectTimeoutMs??settingsManager.getWebSocketConnectTimeoutMs();try{return modelRuntime.streamSimple(model2,context,{...options2,timeoutMs,websocketConnectTimeoutMs,maxRetries:options2?.maxRetries??providerRetrySettings.maxRetries,maxRetryDelayMs:options2?.maxRetryDelayMs??providerRetrySettings.maxRetryDelayMs,transformHeaders:async requestHeaders=>{let session2=agentSessionRef.current;if(!session2)throw new Error("Capability runtime is not initialized for provider request");return session2.getCapabilityRuntime().transformProviderHeaders({model:model2,...options2?.sessionId===void 0?{}:{sessionId:options2.sessionId},headers:requestHeaders})}})}catch(error2){throw hostLogger?.error("sdk","provider stream failed",{cause:error2}),error2}},onPayload:async(payload2,model2)=>{try{traceService?.adapter.captureProviderPayload(payload2,model2?.id)}catch(error2){hostLogger?.warn("sdk","trace payload capture failed",{cause:error2})}},sessionId:sessionManager.getSessionId(),transformContext:async messages=>{let result=messages;if(backgroundDigest.pending.length>0){let drained=backgroundDigest.pending.splice(0);result=injectAfterLastUserMessage(result,{role:"user",content:["Background subagent tasks settled:",...drained.map(line=>`- ${line}`)].join(`
|
|
1068
|
-
`),timestamp:Date.now()})}return result},steeringMode:settingsManager.getSteeringMode(),followUpMode:settingsManager.getFollowUpMode(),transport:settingsManager.getTransport(),thinkingBudgets:settingsManager.getThinkingBudgets(),maxRetryDelayMs:settingsManager.getProviderRetrySettings().maxRetryDelayMs}),hasExistingSession?(agent.state.messages=existingSession.messages,hasThinkingEntry||sessionManager.appendThinkingLevelChange(thinkingLevel)):(model&&sessionManager.appendModelChange(model.provider,model.id),sessionManager.appendThinkingLevelChange(thinkingLevel));let session=new AgentSession({agent,sessionManager,settingsManager,cwd,scopedModels:options.scopedModels,resourceLoader,customTools:options.customTools,modelRuntime,initialActiveToolNames,allowedToolNames,excludedToolNames,sessionStartEvent:options.sessionStartEvent,capabilityMode:options.capabilityMode,contextStrategyName:options.contextStrategyName,retryPolicyName:options.retryPolicyName,compactionPolicyName:options.compactionPolicyName,overflowPolicyName:options.overflowPolicyName,branchSummaryPolicyName:options.branchSummaryPolicyName,runLoopStrategyName:options.runLoopStrategyName,agentTaskAdapter:options.enableAgentTasks===!1?void 0:options.agentTaskAdapter,...options.agentTaskResults===void 0?{}:{agentTaskResults:options.agentTaskResults},...options.enableAgentTasks===!1?{}:{agentSessionReader:async sessionId=>{let parentSession=agentSessionRef.current;if(parentSession===void 0)return;let read=readAgentSession({agentDir,sessionId});if(!(read===void 0||read.parentAgentSession!==parentSession.sessionId))return{sessionId:read.sessionId,...read.parentAgentSession===void 0?{}:{parentAgentSession:read.parentAgentSession},...read.agentRole===void 0?{}:{agentRole:read.agentRole},...read.createdAt===void 0?{}:{createdAt:read.createdAt},bytes:read.bytes,entryCount:read.entryCount,truncated:read.truncated,entries:read.entries}},agentSessionLister:async()=>{let parentSession=agentSessionRef.current;return parentSession===void 0?[]:listAgentSessions({agentDir,parentAgentSession:parentSession.sessionId}).map(summary=>({sessionId:summary.sessionId,...summary.agentRole===void 0?{}:{agentRole:summary.agentRole},...summary.createdAt===void 0?{}:{createdAt:summary.createdAt},modifiedAt:summary.modifiedAt,bytes:summary.bytes}))}},agentComposition:options.agentComposition,interactionHost:options.interactionHost,hostLogger:options.hostLogger,logRecordMirrorRef:observabilityLogMirror,observabilityGetMetricsRef:observabilityGetMetrics,agentDir,...communicationWiring===void 0?{}:{communication:communicationWiring},...options.enableAgentTasks===!1?{}:{turnContext:{backgroundDigestSink:line=>{backgroundDigest.pending.length>=20&&backgroundDigest.pending.shift(),backgroundDigest.pending.push(line),deliverAgentTaskSettledDigestLine(agentSessionRef.current,line,hostLogger)},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId()}},...options.enableAgentTasks===!1?{}:{roleAssociations:suiteWorkspace.suite.associations.roles},...traceService===void 0?{}:{traceService},...options.memoryCapability?.storage===void 0?{}:{memoryStorage:options.memoryCapability.storage},orientationPrompt:ORIENTATION_PROMPTS[suiteWorkspace.suite.orientation],...capabilitySkillsFilter===void 0?{}:{capabilitySkillsFilter}});agentSessionRef.current=session,(!hasExistingSession||sessionSuiteBinding!==void 0&&!hasConversation)&&session.sessionManager.appendCustomEntry(SUITE_SESSION_ENTRY_TYPE,{suiteId,profileIdentity:suiteWorkspace.identity});let pluginRejections=[],recordRejection=async(code,manifestPath,pluginId,message)=>{let rejection=Object.freeze({code,manifestPath,...pluginId===void 0?{}:{pluginId},message});pluginRejections.push(rejection),hostLogger?.error("sdk",`capability plugin rejected: ${message}`,{sessionId:session.sessionId,fields:{code:rejection.code,pluginId:rejection.pluginId,manifestPath:rejection.manifestPath}});try{await session.getCapabilityRuntime().recordPluginRejection(rejection)}catch{}},rejectionMessage=error2=>error2 instanceof Error?error2.message:String(error2);try{let discoveredManifestPaths=options.discoverCapabilityPlugins===!1?[]:discoverCapabilityPluginManifests([join49(agentDir,"plugins"),join49(cwd,CONFIG_DIR_NAME,"plugins")]),suiteLocalManifestPaths=capabilityWiring&&options.discoverCapabilityPlugins!==!1&&suiteAssembly.localPluginsDir!==void 0?discoverCapabilityPluginManifests([suiteAssembly.localPluginsDir]):[],disabledPluginIdSet=new Set(options.disabledPluginIds??[]),profilePluginIds=suiteAssembly.pluginProfile!==void 0&&suiteAssembly.pluginProfile.status==="resolved"?new Set(suiteAssembly.pluginProfile.profile.pluginIds.filter(pluginId=>!disabledPluginIdSet.has(pluginId))):new Set,capabilityPackageIds=suiteWorkspace.suite.capabilities.flatMap(shortId=>{let pluginId=BUILTIN_CAPABILITY_PACKAGE_IDS[shortId];return pluginId===void 0?[]:[pluginId]});if(options.traceEnabled!==!1&&capabilityPackageIds.push(OBSERVABILITY_PACKAGE_ID),memoryModeResolution.mode==="off"){let memoryIndex=capabilityPackageIds.indexOf(MEMORY_PACKAGE_ID);memoryIndex>=0&&capabilityPackageIds.splice(memoryIndex,1)}for(let pluginId of capabilityPackageIds)disabledPluginIdSet.has(pluginId)||profilePluginIds.add(pluginId);let installedPluginManifestPaths=[],skippedInstalledPluginIds=[];for(let plugin of options.installedCapabilityPlugins??[])profilePluginIds.has(plugin.pluginId)?installedPluginManifestPaths.push(plugin.manifestPath):skippedInstalledPluginIds.push(plugin.pluginId);skippedInstalledPluginIds.length>0&&capabilityDiagnostics.push(`Installed capability plugins stay unloaded because the active profile did not select them: ${skippedInstalledPluginIds.sort().join(", ")}`);let manifestPaths=[...suiteLocalManifestPaths,...installedPluginManifestPaths,...discoveredManifestPaths,...options.capabilityPluginPaths??[]],explicitCandidatePaths=new Set([...suiteLocalManifestPaths,...installedPluginManifestPaths,...options.capabilityPluginPaths??[]]),loadedManifestPaths=new Set,explicitManifestPaths=new Set,candidatePaths=[];for(let manifestPath of manifestPaths){let resolvedManifestPath=resolve18(cwd,manifestPath),manifestIdentity=existsSync22(resolvedManifestPath)?realpathSync4(resolvedManifestPath):resolvedManifestPath;loadedManifestPaths.has(manifestIdentity)||(loadedManifestPaths.add(manifestIdentity),explicitCandidatePaths.has(manifestPath)&&explicitManifestPaths.add(manifestIdentity),candidatePaths.push(manifestIdentity))}let manifestEntries=[];for(let manifestPath of candidatePaths)try{let manifest=await readCapabilityPluginManifestForOrdering(manifestPath);if(manifest.hostVersion!==void 0){if(!(0,import_semver5.satisfies)(VERSION,manifest.hostVersion)){await recordRejection("host_version_incompatible",manifestPath,manifest.id,`Plugin ${manifest.id} declares host version range "${manifest.hostVersion}", but the host is ${VERSION}. Upgrade the host into the declared range, or install a plugin version that supports host ${VERSION}.`);continue}}else capabilityDiagnostics.push(`Capability plugin ${manifest.id} (${manifestPath}) does not declare "hostVersion"; it loads, but published plugins must declare a host semver range (e.g. ">=${VERSION}").`);manifestEntries.push({path:manifestPath,manifest})}catch(error2){await recordRejection("invalid_manifest",manifestPath,void 0,rejectionMessage(error2))}let poolFilter=capabilityWiring?{suite:suiteWorkspace.suite,decide:(manifestId,manifestPath)=>decideSuiteCapabilityPlugin(suiteWorkspace.suite,{manifestId,manifestPath},{cwd})}:void 0,seenPluginIds=new Set,uniqueEntries=[],discoveredPluginIds=[];for(let entry of manifestEntries){if(discoveredPluginIds.push(entry.manifest.id),poolFilter&&!explicitManifestPaths.has(entry.path)){let decision=poolFilter.decide(entry.manifest.id,entry.path);if(!decision.keep){decision.diagnostic&&capabilityDiagnostics.push(decision.diagnostic);continue}}if(seenPluginIds.has(entry.manifest.id)){await recordRejection("duplicate_plugin_id",entry.path,entry.manifest.id,`Capability plugin is already loaded: ${entry.manifest.id}; the first manifest in discovery order wins`);continue}seenPluginIds.add(entry.manifest.id),uniqueEntries.push(entry)}poolFilter&&capabilityDiagnostics.push(...suiteDanglingPluginAssociations(poolFilter.suite,discoveredPluginIds));let capabilityIdentity=(id,version)=>`${id}\0${version}`,survivors=new Set(uniqueEntries),removedInLastPass=!0;for(;removedInLastPass;){removedInLastPass=!1;let providers=new Set;for(let entry of survivors)for(let declaration of entry.manifest.provides??[])providers.add(capabilityIdentity(declaration.id,declaration.version));for(let entry of[...survivors]){let missing=(entry.manifest.requires??[]).filter(requirement=>!requirement.optional&&!providers.has(capabilityIdentity(requirement.id,requirement.version)));missing.length!==0&&(await recordRejection("missing_dependency",entry.path,entry.manifest.id,`Plugin capability is required but unavailable: ${missing.map(requirement=>`${requirement.id}@${requirement.version}`).join(", ")} (${entry.manifest.id})`),survivors.delete(entry),removedInLastPass=!0)}}let pathByManifest=new Map([...survivors].map(entry=>[entry.manifest,entry.path]));for(let manifest of resolvePluginCapabilityOrder([...survivors].map(entry=>entry.manifest))){let manifestPath=pathByManifest.get(manifest);if(!manifestPath)throw new Error(`Capability plugin manifest path is unavailable: ${manifest.id}`);try{await session.loadCapabilityPluginManifest(manifestPath,{...manifest.id===SUBAGENT_DELEGATE_PACKAGE_ID&&options.subagentPoolFromSelfInvocation===!0?{configOverride:{runnerEntryAuto:!0}}:{},...manifest.id===MEMORY_PACKAGE_ID?{configOverride:{...memoryModeOption===void 0?{}:{memoryMode:memoryModeOption},...settingsMemoryMode===void 0?{}:{memorySettingsMode:settingsMemoryMode}}}:{}})}catch(error2){await recordRejection("plugin_load_failed",manifestPath,manifest.id,rejectionMessage(error2))}}hasExistingSession&&options.contextStrategyName&&await session.replaceContext(existingSession.messages)}catch(error2){throw await session.dispose(),error2}return hostLogger?.info("sdk","agent session created",{sessionId:session.sessionId,fields:{suite:suiteId,...model===void 0?{}:{model:`${model.provider}/${model.id}`},trace:options.traceEnabled!==!1}}),{session,modelFallbackMessage,pluginRejections:Object.freeze(pluginRejections.slice()),suiteDiagnostics:Object.freeze([...suiteAssembly.collectDiagnostics(),...capabilityDiagnostics,...suitePreferenceDiagnostics]),...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile},resolvedAgentProfile}}async function createStableAgentSession(options={}){let result=await createAgentSession(options);return{facade:createCodingAgentFacade(result.session),sessionAPI:result.session.getSessionAPI(),modelFallbackMessage:result.modelFallbackMessage}}async function createStableAgentSessionRuntime(createRuntime,options){let runtime=await createAgentSessionRuntime(createRuntime,options);return{runtimeFacade:createCodingAgentRuntimeFacade(runtime)}}var MCP_CONFIG_FILENAME="mcp.json",MCP_POOL_DIR="mcp/pool",MCP_POOL_BRIDGE_DIR="_bridge",MCP_SERVER_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,MCP_HTTP_PLUGIN_SOURCE_PATH=fileURLToPath5(new URL("../plugins/mcp-http.ts",import.meta.url)),MCP_HTTP_PLUGIN_DIST_PATH=fileURLToPath5(new URL("../../dist/plugins/mcp-http.js",import.meta.url));function isHttpUrl(value){try{let protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"}catch{return!1}}function parseMcpConfig(path15){let servers=new Map,diagnostics=[],value;try{value=JSON.parse(readFileSync20(path15,"utf8"))}catch(error2){return error2.code==="ENOENT"?{servers,diagnostics}:(diagnostics.push(`MCP config at ${path15} is unreadable; ignoring it. Errors: ${error2 instanceof Error?error2.message:String(error2)}`),{servers,diagnostics})}if(typeof value!="object"||value===null||Array.isArray(value))return diagnostics.push(`MCP config at ${path15} must be an object with an "mcpServers" map; ignoring it.`),{servers,diagnostics};let mcpServers=value.mcpServers;if(mcpServers===void 0)return{servers,diagnostics};if(typeof mcpServers!="object"||mcpServers===null||Array.isArray(mcpServers))return diagnostics.push(`MCP config at ${path15} must carry an "mcpServers" object; ignoring it.`),{servers,diagnostics};for(let[name,entry]of Object.entries(mcpServers)){if(!MCP_SERVER_NAME_PATTERN.test(name)){diagnostics.push(`MCP server name "${name}" in ${path15} is invalid (must match ${MCP_SERVER_NAME_PATTERN.source}); ignoring it.`);continue}if(typeof entry!="object"||entry===null||Array.isArray(entry)){diagnostics.push(`MCP server "${name}" in ${path15} must be an object with a "command" or "url"; ignoring it.`);continue}let config=entry;if(config.url!==void 0&&(typeof config.url!="string"||config.url.trim().length===0)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a non-empty string; ignoring it.`);continue}let hasCommand=typeof config.command=="string"&&config.command.trim().length>0,hasUrl=typeof config.url=="string"&&config.url.trim().length>0;if(hasCommand&&hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} accepts either "command" (stdio server) or "url" (remote HTTP server), not both; ignoring it.`);continue}if(!hasCommand&&!hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} requires a non-empty string "command" (stdio server) or "url" (remote HTTP server); ignoring it.`);continue}if(hasUrl&&!isHttpUrl(config.url)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a valid http:// or https:// URL; ignoring it.`);continue}if(config.args!==void 0&&(!Array.isArray(config.args)||!config.args.every(arg=>typeof arg=="string"))){diagnostics.push(`MCP server "${name}" in ${path15} requires "args" to be a string array; ignoring it.`);continue}if(config.deferredTools!==void 0&&typeof config.deferredTools!="boolean"){diagnostics.push(`MCP server "${name}" in ${path15} requires "deferredTools" to be a boolean; ignoring it.`);continue}if(config.headers!==void 0){if(hasCommand)diagnostics.push(`MCP server "${name}" in ${path15} carries "headers" but headers only apply to remote "url" (HTTP) servers; ignoring them.`);else if(!(typeof config.headers=="object"&&config.headers!==null&&!Array.isArray(config.headers)&&Object.values(config.headers).every(headerValue=>typeof headerValue=="string"&&headerValue.length>0))){diagnostics.push(`MCP server "${name}" in ${path15} requires "headers" to be an object with non-empty string values; ignoring it.`);continue}}servers.set(name,{args:config.args??[],deferredTools:config.deferredTools===!0?!0:void 0,...hasCommand?{command:config.command}:{url:config.url,...config.headers===void 0?{}:{headers:config.headers}}})}return{servers,diagnostics}}var MCP_POOL_BRIDGE_SOURCE=`// Generated by the suite MCP registration pool (agent-session-services). Do not edit.
|
|
1067
|
+
`)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}setDefaultStreamFn(streamSimple);var AGENT_TASK_SETTLED_STATUSES=new Set(["queued","admitted","running","succeeded","failed","cancelled","timed_out","drain_timeout","runner_lost"]);function parseAgentTaskSettledDigestLine(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let record=parsed;if(!(typeof record.taskId!="string"||record.taskId==="")&&!(typeof record.sessionId!="string"||record.sessionId==="")&&!(typeof record.status!="string"||!AGENT_TASK_SETTLED_STATUSES.has(record.status))&&!(record.reasonCode!==void 0&&(typeof record.reasonCode!="string"||record.reasonCode==="")))return{taskId:record.taskId,taskSessionId:record.sessionId,status:record.status,...record.reasonCode===void 0?{}:{reasonCode:record.reasonCode}}}function deliverAgentTaskSettledDigestLine(session,line,hostLogger){let facts=parseAgentTaskSettledDigestLine(line);if(facts===void 0){hostLogger?.warn("sdk","background delegation settlement line is not a valid agent.task.settled source",{cause:line});return}session?.dispatchAgentTaskSettled(facts)}var OBSERVABILITY_PACKAGE_ID="agent-forge.plugin.observability",SUBAGENT_DELEGATE_PACKAGE_ID="agent-forge.plugin.subagent-delegate",MEMORY_PACKAGE_ID="agent-forge.plugin.memory",isMemoryModeV1=value=>value==="off"||value==="light"||value==="full";function resolveSdkMemoryMode(explicitMode,env2,settingsMode){if(explicitMode!==void 0)return isMemoryModeV1(explicitMode)?{mode:explicitMode}:{mode:"off",invalidEnvValue:explicitMode};let configured=env2.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();if(configured!==void 0&&configured!=="")return isMemoryModeV1(configured)?{mode:configured}:{mode:"off",invalidEnvValue:configured};let fromSettings=settingsMode?.trim().toLowerCase();if(fromSettings!==void 0&&fromSettings!=="")return isMemoryModeV1(fromSettings)?{mode:fromSettings}:{mode:"off",invalidSettingsValue:fromSettings};let legacy=env2.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();return legacy!==void 0&&legacy!==""?isMemoryModeV1(legacy)?{mode:legacy}:{mode:"off",invalidEnvValue:legacy}:{mode:"off"}}function getDefaultAgentDir(){return getAgentDir()}function injectAfterLastUserMessage(messages,injection){for(let index3=messages.length-1;index3>=0;index3-=1)if(messages[index3]?.role==="user")return[...messages.slice(0,index3+1),injection,...messages.slice(index3+1)];return messages}async function readCapabilityPluginManifestForOrdering(manifestPath){let raw;try{raw=JSON.parse(await readFile9(manifestPath,"utf8"))}catch(error2){throw new Error(`Failed to read capability plugin manifest ${manifestPath}: ${error2 instanceof Error?error2.message:String(error2)}`)}return parseCapabilityPluginManifest(raw,manifestPath)}async function createAgentSession(options={}){let cwd=resolvePath(options.cwd??options.sessionManager?.getCwd()??process.cwd()),agentDir=options.agentDir?resolvePath(options.agentDir):getDefaultAgentDir(),resourceLoader=options.resourceLoader,authPath=options.agentDir?join49(agentDir,"auth.json"):void 0,modelsPath=options.agentDir?join49(agentDir,"models.json"):void 0,modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath,modelsPath,credentials:options.credentials}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),suiteId=resolveSuiteId({explicit:options.suite,envSuite:process.env[SUITE_ENV_VAR],settings:settingsManager,agentDir}),suiteAssembly=createSuiteAssembly({cwd,agentDir,suiteId,pluginProfileId:options.pluginProfileId,selectedPluginIds:options.selectedPluginIds,disabledPluginIds:options.disabledPluginIds,pluginHost:options.pluginHost,verifiedPlugins:options.verifiedPlugins,manifestOverrides:options.manifestOverrides,pluginProfile:options.pluginProfile}),suiteWorkspace=suiteAssembly.workspace,resolvedAgentProfile=buildResolvedAgentProfileV1({suiteId,workspace:suiteWorkspace,...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile}}),capabilityWiring=options.suiteCapabilityWiring??!options.resourceLoader,capabilityDiagnostics=[],suitePreferenceDiagnostics=[],capabilitySkillsFilter,communicationMailbox,selfMailbox=()=>(communicationMailbox??=createSubagentMailbox({agentDir,ownerParentSessionId:()=>agentSessionRef.current?.sessionId}),communicationMailbox),communicationWiring=options.enableAgentTasks===!1&&options.subagentCommunicationWiring===void 0?void 0:{drainEscalations:sessionId=>selfMailbox().drainEscalations(sessionId),...options.subagentCommunicationWiring??{}},backgroundDigest={pending:[]},settingsMemoryMode=settingsManager.getMemoryModeSetting(),memoryModeOption=options.memoryCapability?.mode,memoryModeResolution=resolveSdkMemoryMode(memoryModeOption,process.env,settingsMemoryMode);if(capabilityWiring){suiteWorkspace.suite.capabilities.includes("builtin.memory")&&(memoryModeResolution.invalidEnvValue!==void 0&&capabilityDiagnostics.push(`invalid AGENT_FORGE_MEMORY_MODE value "${memoryModeResolution.invalidEnvValue}"; memory stays off (fail-closed)`),memoryModeResolution.invalidSettingsValue!==void 0&&capabilityDiagnostics.push(`invalid memory.mode setting "${memoryModeResolution.invalidSettingsValue}"; memory stays off (fail-closed)`),memoryModeResolution.mode==="off"&&capabilityDiagnostics.push("memory disabled (mode=off) \u2014 set memory.mode (light|full) in settings.json to enable"));let suiteDefinition=suiteWorkspace.suite,suiteLocalSkillsDir=suiteAssembly.localSkillsDir;capabilitySkillsFilter=skills=>filterSuiteSkills(suiteDefinition,skills,{localSkillsDir:suiteLocalSkillsDir}).kept}let sessionManager=options.sessionManager??SessionManager.create(cwd,getDefaultSessionDir(cwd,agentDir)),hostLogger=options.hostLogger,traceOptions=options.traceOptions,observabilityCapture={},observabilityLogMirror={},observabilityGetMetrics={},traceService;options.traceEnabled!==!1&&(traceService={adapter:{getTraceFilePath:()=>{let sessionFilePath=sessionManager.getSessionFile();return sessionFilePath===void 0?null:getTraceFilePathForSession(sessionFilePath)},captureProviderPayload:(payload2,model2)=>{observabilityCapture.current?.(payload2,model2)},onSinkFailure:error2=>{hostLogger?.error("observability","trace sink failure",{cause:error2})},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId(),getParentAgentSessionId:()=>sessionManager.getHeader()?.parentAgentSession,getParentTraceId:()=>sessionManager.getHeader()?.parentTraceId,registerFacade:facade=>{observabilityCapture.current=facade?.captureProviderPayload,observabilityLogMirror.current=facade?.mirrorPluginLog,observabilityGetMetrics.current=facade?.getMetrics}},...traceOptions===void 0?{}:{options:traceOptions}}),resourceLoader||(resourceLoader=new DefaultResourceLoader({cwd,agentDir,settingsManager,...suiteAssembly.loaderOverrides,...suiteAssembly.localSkillsDir===void 0?{}:{additionalSkillPaths:[suiteAssembly.localSkillsDir]}}),await resourceLoader.reload(),time("resourceLoader.reload"));let existingSession=sessionManager.buildSessionContext(),hasExistingSession=existingSession.messages.length>0,branchEntries=sessionManager.getBranch(),sessionSuiteBinding=readSessionSuiteBinding(branchEntries),hasConversation=branchEntries.some(entry=>entry.type==="message"&&entry.message?.role==="user");if(hasConversation&&sessionSuiteBinding!==void 0){if(sessionSuiteBinding.suiteId!==suiteId)throw new SuiteRebindError(`Session is bound to suite "${sessionSuiteBinding.suiteId}" and cannot resume with "${suiteId}"; create a new session or migrate explicitly`);if(sessionSuiteBinding.profileIdentity!==void 0&&!profileIdentitiesCompatible(sessionSuiteBinding.profileIdentity,suiteWorkspace.identity))throw new SuiteRebindError("Session Profile identity drift detected; create a new session or migrate explicitly before reloading plugins")}let hasThinkingEntry=sessionManager.getBranch().some(entry=>entry.type==="thinking_level_change"),model=options.model,modelFallbackMessage;if(!model&&hasExistingSession&&existingSession.model){let restoredModel=modelRuntime.getModel(existingSession.model.provider,existingSession.model.modelId);restoredModel&&modelRuntime.hasConfiguredAuth(restoredModel.provider)&&(model=restoredModel),model||(modelFallbackMessage=`Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`)}let suiteModelPreference=suiteWorkspace.suite.model;if(!model&&suiteModelPreference!==null){let suiteModel=findExactModelReferenceMatch(suiteModelPreference,[...modelRuntime.getModels()]);suiteModel&&modelRuntime.hasConfiguredAuth(suiteModel.provider)?model=suiteModel:suitePreferenceDiagnostics.push(`Suite "${suiteId}" model "${suiteModelPreference}" does not resolve to an authenticated model; using the normal model resolution instead.`)}model||(model=(await findInitialModel({scopedModels:[],isContinuing:hasExistingSession,defaultProvider:settingsManager.getDefaultProvider(),defaultModelId:settingsManager.getDefaultModel(),defaultThinkingLevel:settingsManager.getDefaultThinkingLevel(),modelThinkingLevels:settingsManager.getAllModelThinkingLevels(),modelRuntime})).model,model?modelFallbackMessage&&(modelFallbackMessage+=`. Using ${model.provider}/${model.id}`):modelFallbackMessage=formatNoModelsAvailableMessage());let thinkingLevel=options.thinkingLevel;thinkingLevel===void 0&&hasExistingSession&&hasThinkingEntry&&(thinkingLevel=existingSession.thinkingLevel);let suiteThinkingPreference=suiteWorkspace.suite.thinking;if(thinkingLevel===void 0&&suiteThinkingPreference!==null&&(isValidThinkingLevel(suiteThinkingPreference)?thinkingLevel=suiteThinkingPreference:suitePreferenceDiagnostics.push(`Suite "${suiteId}" thinking "${suiteThinkingPreference}" is not a valid thinking level; using the normal thinking resolution instead.`)),thinkingLevel===void 0&&hasExistingSession&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),thinkingLevel===void 0&&model){let perModel=settingsManager.getModelThinkingLevel(model.provider,model.id);perModel&&(thinkingLevel=perModel)}thinkingLevel===void 0&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),model?thinkingLevel=clampThinkingLevel(model,thinkingLevel):thinkingLevel="off";let defaultActiveToolNames=options.capabilityMode==="readonly"?["read","grep","find","ls"]:["read","bash","edit","write"],configuredDefaultToolNames=settingsManager.getDefaultTools(),allowedToolNames=options.tools??(options.noTools==="all"?[]:void 0),excludedToolNames=options.excludeTools,excludedToolNameSet=excludedToolNames?new Set(excludedToolNames):void 0,initialActiveToolNames=((options.tools===void 0&&options.noTools===void 0&&options.capabilityMode!=="readonly"?[...suiteWorkspace.suite.tools]:void 0)??options.tools??(options.noTools?[]:configuredDefaultToolNames??defaultActiveToolNames)).filter(name=>!excludedToolNameSet?.has(name)),agent,convertToLlmWithBlockImages=messages=>{let converted=convertToLlm2(messages);return settingsManager.getBlockImages()?converted.map(msg=>{if(msg.role==="user"||msg.role==="toolResult"){let content=msg.content;if(Array.isArray(content)&&content.some(c2=>c2.type==="image")){let filteredContent=content.map(c2=>c2.type==="image"?{type:"text",text:"Image reading is disabled."}:c2).filter((c2,i,arr)=>!(c2.type==="text"&&c2.text==="Image reading is disabled."&&i>0&&arr[i-1].type==="text"&&arr[i-1].text==="Image reading is disabled."));return{...msg,content:filteredContent}}}return msg}):converted},agentSessionRef={},customStreamFn=options.streamFn;agent=new Agent({initialState:{systemPrompt:"",model,thinkingLevel,tools:[]},convertToLlm:convertToLlmWithBlockImages,streamFn:customStreamFn?(model2,context,streamOptions)=>customStreamFn(model2,context,streamOptions):async(model2,context,options2)=>{let providerRetrySettings=settingsManager.getProviderRetrySettings(),httpIdleTimeoutMs=settingsManager.getHttpIdleTimeoutMs(),effectiveTimeoutMs=httpIdleTimeoutMs===0?2147483647:httpIdleTimeoutMs,timeoutMs=options2?.timeoutMs??providerRetrySettings.timeoutMs??effectiveTimeoutMs,websocketConnectTimeoutMs=options2?.websocketConnectTimeoutMs??settingsManager.getWebSocketConnectTimeoutMs();try{return modelRuntime.streamSimple(model2,context,{...options2,timeoutMs,websocketConnectTimeoutMs,maxRetries:options2?.maxRetries??providerRetrySettings.maxRetries,maxRetryDelayMs:options2?.maxRetryDelayMs??providerRetrySettings.maxRetryDelayMs,transformHeaders:async requestHeaders=>{let session2=agentSessionRef.current;if(!session2)throw new Error("Capability runtime is not initialized for provider request");return session2.getCapabilityRuntime().transformProviderHeaders({model:model2,...options2?.sessionId===void 0?{}:{sessionId:options2.sessionId},headers:requestHeaders})}})}catch(error2){throw hostLogger?.error("sdk","provider stream failed",{cause:error2}),error2}},onPayload:async(payload2,model2)=>{try{traceService?.adapter.captureProviderPayload(payload2,model2?.id)}catch(error2){hostLogger?.warn("sdk","trace payload capture failed",{cause:error2})}},sessionId:sessionManager.getSessionId(),transformContext:async messages=>{let result=messages;if(backgroundDigest.pending.length>0){let drained=backgroundDigest.pending.splice(0);result=injectAfterLastUserMessage(result,{role:"user",content:["Background subagent tasks settled:",...drained.map(line=>`- ${line}`)].join(`
|
|
1068
|
+
`),timestamp:Date.now()})}return result},steeringMode:settingsManager.getSteeringMode(),followUpMode:settingsManager.getFollowUpMode(),transport:settingsManager.getTransport(),thinkingBudgets:settingsManager.getThinkingBudgets(),maxRetryDelayMs:settingsManager.getProviderRetrySettings().maxRetryDelayMs}),hasExistingSession?(agent.state.messages=existingSession.messages,hasThinkingEntry||sessionManager.appendThinkingLevelChange(thinkingLevel)):(model&&sessionManager.appendModelChange(model.provider,model.id),sessionManager.appendThinkingLevelChange(thinkingLevel));let session=new AgentSession({agent,sessionManager,settingsManager,cwd,scopedModels:options.scopedModels,resourceLoader,customTools:options.customTools,modelRuntime,initialActiveToolNames,allowedToolNames,excludedToolNames,sessionStartEvent:options.sessionStartEvent,capabilityMode:options.capabilityMode,contextStrategyName:options.contextStrategyName,retryPolicyName:options.retryPolicyName,compactionPolicyName:options.compactionPolicyName,overflowPolicyName:options.overflowPolicyName,branchSummaryPolicyName:options.branchSummaryPolicyName,runLoopStrategyName:options.runLoopStrategyName,agentTaskAdapter:options.enableAgentTasks===!1?void 0:options.agentTaskAdapter,...options.agentTaskResults===void 0?{}:{agentTaskResults:options.agentTaskResults},...options.enableAgentTasks===!1?{}:{agentSessionReader:async sessionId=>{let parentSession=agentSessionRef.current;if(parentSession===void 0)return;let read=readAgentSession({agentDir,sessionId});if(!(read===void 0||read.parentAgentSession!==parentSession.sessionId))return{sessionId:read.sessionId,...read.parentAgentSession===void 0?{}:{parentAgentSession:read.parentAgentSession},...read.agentRole===void 0?{}:{agentRole:read.agentRole},...read.createdAt===void 0?{}:{createdAt:read.createdAt},bytes:read.bytes,entryCount:read.entryCount,truncated:read.truncated,entries:read.entries}},agentSessionLister:async()=>{let parentSession=agentSessionRef.current;return parentSession===void 0?[]:listAgentSessions({agentDir,parentAgentSession:parentSession.sessionId}).map(summary=>({sessionId:summary.sessionId,...summary.agentRole===void 0?{}:{agentRole:summary.agentRole},...summary.createdAt===void 0?{}:{createdAt:summary.createdAt},modifiedAt:summary.modifiedAt,bytes:summary.bytes}))}},agentComposition:options.agentComposition,interactionHost:options.interactionHost,hostLogger:options.hostLogger,logRecordMirrorRef:observabilityLogMirror,observabilityGetMetricsRef:observabilityGetMetrics,agentDir,...communicationWiring===void 0?{}:{communication:communicationWiring},...options.enableAgentTasks===!1?{}:{turnContext:{backgroundDigestSink:line=>{backgroundDigest.pending.length>=20&&backgroundDigest.pending.shift(),backgroundDigest.pending.push(line),deliverAgentTaskSettledDigestLine(agentSessionRef.current,line,hostLogger)},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId()}},...options.enableAgentTasks===!1?{}:{roleAssociations:suiteWorkspace.suite.associations.roles},...traceService===void 0?{}:{traceService},...options.memoryCapability?.storage===void 0?{}:{memoryStorage:options.memoryCapability.storage},orientationPrompt:ORIENTATION_PROMPTS[suiteWorkspace.suite.orientation],...capabilitySkillsFilter===void 0?{}:{capabilitySkillsFilter}});agentSessionRef.current=session,(!hasExistingSession||sessionSuiteBinding!==void 0&&!hasConversation)&&session.sessionManager.appendCustomEntry(SUITE_SESSION_ENTRY_TYPE,{suiteId,profileIdentity:suiteWorkspace.identity});let pluginRejections=[],recordRejection=async(code,manifestPath,pluginId,message)=>{let rejection=Object.freeze({code,manifestPath,...pluginId===void 0?{}:{pluginId},message});pluginRejections.push(rejection),hostLogger?.error("sdk",`capability plugin rejected: ${message}`,{sessionId:session.sessionId,fields:{code:rejection.code,pluginId:rejection.pluginId,manifestPath:rejection.manifestPath}});try{await session.getCapabilityRuntime().recordPluginRejection(rejection)}catch{}},rejectionMessage=error2=>error2 instanceof Error?error2.message:String(error2);try{let discoveredManifestPaths=options.discoverCapabilityPlugins===!1?[]:discoverCapabilityPluginManifests([join49(agentDir,"plugins"),join49(cwd,CONFIG_DIR_NAME,"plugins")]),suiteLocalManifestPaths=capabilityWiring&&options.discoverCapabilityPlugins!==!1&&suiteAssembly.localPluginsDir!==void 0?discoverCapabilityPluginManifests([suiteAssembly.localPluginsDir]):[],disabledPluginIdSet=new Set(options.disabledPluginIds??[]),profilePluginIds=suiteAssembly.pluginProfile!==void 0&&suiteAssembly.pluginProfile.status==="resolved"?new Set(suiteAssembly.pluginProfile.profile.pluginIds.filter(pluginId=>!disabledPluginIdSet.has(pluginId))):new Set,passthroughCapabilityPluginIds=[],capabilityPackageIds=suiteWorkspace.suite.capabilities.flatMap(entry=>{let mappedPluginId=BUILTIN_CAPABILITY_PACKAGE_IDS[entry];return mappedPluginId!==void 0?[mappedPluginId]:(passthroughCapabilityPluginIds.push(entry),[entry])});if(options.traceEnabled!==!1&&capabilityPackageIds.push(OBSERVABILITY_PACKAGE_ID),memoryModeResolution.mode==="off"){let memoryIndex=capabilityPackageIds.indexOf(MEMORY_PACKAGE_ID);memoryIndex>=0&&capabilityPackageIds.splice(memoryIndex,1)}for(let pluginId of capabilityPackageIds)disabledPluginIdSet.has(pluginId)||profilePluginIds.add(pluginId);if(capabilityWiring&&passthroughCapabilityPluginIds.length>0){let installedPluginIdSet=new Set((options.installedCapabilityPlugins??[]).map(plugin=>plugin.pluginId));for(let pluginId of passthroughCapabilityPluginIds)installedPluginIdSet.has(pluginId)||capabilityDiagnostics.push(`Suite "${suiteId}" capability "${pluginId}" has no installed active plugin; install it with agent-forge plugin install or remove the declaration`)}let installedPluginManifestPaths=[],skippedInstalledPluginIds=[];for(let plugin of options.installedCapabilityPlugins??[])profilePluginIds.has(plugin.pluginId)?installedPluginManifestPaths.push(plugin.manifestPath):skippedInstalledPluginIds.push(plugin.pluginId);skippedInstalledPluginIds.length>0&&capabilityDiagnostics.push(`Installed capability plugins stay unloaded because the active profile did not select them: ${skippedInstalledPluginIds.sort().join(", ")}`);let manifestPaths=[...suiteLocalManifestPaths,...installedPluginManifestPaths,...discoveredManifestPaths,...options.capabilityPluginPaths??[]],explicitCandidatePaths=new Set([...suiteLocalManifestPaths,...installedPluginManifestPaths,...options.capabilityPluginPaths??[]]),loadedManifestPaths=new Set,explicitManifestPaths=new Set,candidatePaths=[];for(let manifestPath of manifestPaths){let resolvedManifestPath=resolve18(cwd,manifestPath),manifestIdentity=existsSync22(resolvedManifestPath)?realpathSync4(resolvedManifestPath):resolvedManifestPath;loadedManifestPaths.has(manifestIdentity)||(loadedManifestPaths.add(manifestIdentity),explicitCandidatePaths.has(manifestPath)&&explicitManifestPaths.add(manifestIdentity),candidatePaths.push(manifestIdentity))}let manifestEntries=[];for(let manifestPath of candidatePaths)try{let manifest=await readCapabilityPluginManifestForOrdering(manifestPath);if(manifest.hostVersion!==void 0){if(!(0,import_semver5.satisfies)(VERSION,manifest.hostVersion)){await recordRejection("host_version_incompatible",manifestPath,manifest.id,`Plugin ${manifest.id} declares host version range "${manifest.hostVersion}", but the host is ${VERSION}. Upgrade the host into the declared range, or install a plugin version that supports host ${VERSION}.`);continue}}else capabilityDiagnostics.push(`Capability plugin ${manifest.id} (${manifestPath}) does not declare "hostVersion"; it loads, but published plugins must declare a host semver range (e.g. ">=${VERSION}").`);manifestEntries.push({path:manifestPath,manifest})}catch(error2){await recordRejection("invalid_manifest",manifestPath,void 0,rejectionMessage(error2))}let poolFilter=capabilityWiring?{suite:suiteWorkspace.suite,decide:(manifestId,manifestPath)=>decideSuiteCapabilityPlugin(suiteWorkspace.suite,{manifestId,manifestPath},{cwd})}:void 0,seenPluginIds=new Set,uniqueEntries=[],discoveredPluginIds=[];for(let entry of manifestEntries){if(discoveredPluginIds.push(entry.manifest.id),poolFilter&&!explicitManifestPaths.has(entry.path)){let decision=poolFilter.decide(entry.manifest.id,entry.path);if(!decision.keep){decision.diagnostic&&capabilityDiagnostics.push(decision.diagnostic);continue}}if(seenPluginIds.has(entry.manifest.id)){await recordRejection("duplicate_plugin_id",entry.path,entry.manifest.id,`Capability plugin is already loaded: ${entry.manifest.id}; the first manifest in discovery order wins`);continue}seenPluginIds.add(entry.manifest.id),uniqueEntries.push(entry)}poolFilter&&capabilityDiagnostics.push(...suiteDanglingPluginAssociations(poolFilter.suite,discoveredPluginIds));let capabilityIdentity=(id,version)=>`${id}\0${version}`,survivors=new Set(uniqueEntries),removedInLastPass=!0;for(;removedInLastPass;){removedInLastPass=!1;let providers=new Set;for(let entry of survivors)for(let declaration of entry.manifest.provides??[])providers.add(capabilityIdentity(declaration.id,declaration.version));for(let entry of[...survivors]){let missing=(entry.manifest.requires??[]).filter(requirement=>!requirement.optional&&!providers.has(capabilityIdentity(requirement.id,requirement.version)));missing.length!==0&&(await recordRejection("missing_dependency",entry.path,entry.manifest.id,`Plugin capability is required but unavailable: ${missing.map(requirement=>`${requirement.id}@${requirement.version}`).join(", ")} (${entry.manifest.id})`),survivors.delete(entry),removedInLastPass=!0)}}let pathByManifest=new Map([...survivors].map(entry=>[entry.manifest,entry.path]));for(let manifest of resolvePluginCapabilityOrder([...survivors].map(entry=>entry.manifest))){let manifestPath=pathByManifest.get(manifest);if(!manifestPath)throw new Error(`Capability plugin manifest path is unavailable: ${manifest.id}`);try{await session.loadCapabilityPluginManifest(manifestPath,{...manifest.id===SUBAGENT_DELEGATE_PACKAGE_ID&&options.subagentPoolFromSelfInvocation===!0?{configOverride:{runnerEntryAuto:!0}}:{},...manifest.id===MEMORY_PACKAGE_ID?{configOverride:{...memoryModeOption===void 0?{}:{memoryMode:memoryModeOption},...settingsMemoryMode===void 0?{}:{memorySettingsMode:settingsMemoryMode}}}:{}})}catch(error2){await recordRejection("plugin_load_failed",manifestPath,manifest.id,rejectionMessage(error2))}}hasExistingSession&&options.contextStrategyName&&await session.replaceContext(existingSession.messages)}catch(error2){throw await session.dispose(),error2}return hostLogger?.info("sdk","agent session created",{sessionId:session.sessionId,fields:{suite:suiteId,...model===void 0?{}:{model:`${model.provider}/${model.id}`},trace:options.traceEnabled!==!1}}),{session,modelFallbackMessage,pluginRejections:Object.freeze(pluginRejections.slice()),suiteDiagnostics:Object.freeze([...suiteAssembly.collectDiagnostics(),...capabilityDiagnostics,...suitePreferenceDiagnostics]),...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile},resolvedAgentProfile}}async function createStableAgentSession(options={}){let result=await createAgentSession(options);return{facade:createCodingAgentFacade(result.session),sessionAPI:result.session.getSessionAPI(),modelFallbackMessage:result.modelFallbackMessage}}async function createStableAgentSessionRuntime(createRuntime,options){let runtime=await createAgentSessionRuntime(createRuntime,options);return{runtimeFacade:createCodingAgentRuntimeFacade(runtime)}}var MCP_CONFIG_FILENAME="mcp.json",MCP_POOL_DIR="mcp/pool",MCP_POOL_BRIDGE_DIR="_bridge",MCP_SERVER_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,MCP_HTTP_PLUGIN_SOURCE_PATH=fileURLToPath5(new URL("../plugins/mcp-http.ts",import.meta.url)),MCP_HTTP_PLUGIN_DIST_PATH=fileURLToPath5(new URL("../../dist/plugins/mcp-http.js",import.meta.url));function isHttpUrl(value){try{let protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"}catch{return!1}}function parseMcpConfig(path15){let servers=new Map,diagnostics=[],value;try{value=JSON.parse(readFileSync20(path15,"utf8"))}catch(error2){return error2.code==="ENOENT"?{servers,diagnostics}:(diagnostics.push(`MCP config at ${path15} is unreadable; ignoring it. Errors: ${error2 instanceof Error?error2.message:String(error2)}`),{servers,diagnostics})}if(typeof value!="object"||value===null||Array.isArray(value))return diagnostics.push(`MCP config at ${path15} must be an object with an "mcpServers" map; ignoring it.`),{servers,diagnostics};let mcpServers=value.mcpServers;if(mcpServers===void 0)return{servers,diagnostics};if(typeof mcpServers!="object"||mcpServers===null||Array.isArray(mcpServers))return diagnostics.push(`MCP config at ${path15} must carry an "mcpServers" object; ignoring it.`),{servers,diagnostics};for(let[name,entry]of Object.entries(mcpServers)){if(!MCP_SERVER_NAME_PATTERN.test(name)){diagnostics.push(`MCP server name "${name}" in ${path15} is invalid (must match ${MCP_SERVER_NAME_PATTERN.source}); ignoring it.`);continue}if(typeof entry!="object"||entry===null||Array.isArray(entry)){diagnostics.push(`MCP server "${name}" in ${path15} must be an object with a "command" or "url"; ignoring it.`);continue}let config=entry;if(config.url!==void 0&&(typeof config.url!="string"||config.url.trim().length===0)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a non-empty string; ignoring it.`);continue}let hasCommand=typeof config.command=="string"&&config.command.trim().length>0,hasUrl=typeof config.url=="string"&&config.url.trim().length>0;if(hasCommand&&hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} accepts either "command" (stdio server) or "url" (remote HTTP server), not both; ignoring it.`);continue}if(!hasCommand&&!hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} requires a non-empty string "command" (stdio server) or "url" (remote HTTP server); ignoring it.`);continue}if(hasUrl&&!isHttpUrl(config.url)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a valid http:// or https:// URL; ignoring it.`);continue}if(config.args!==void 0&&(!Array.isArray(config.args)||!config.args.every(arg=>typeof arg=="string"))){diagnostics.push(`MCP server "${name}" in ${path15} requires "args" to be a string array; ignoring it.`);continue}if(config.deferredTools!==void 0&&typeof config.deferredTools!="boolean"){diagnostics.push(`MCP server "${name}" in ${path15} requires "deferredTools" to be a boolean; ignoring it.`);continue}if(config.headers!==void 0){if(hasCommand)diagnostics.push(`MCP server "${name}" in ${path15} carries "headers" but headers only apply to remote "url" (HTTP) servers; ignoring them.`);else if(!(typeof config.headers=="object"&&config.headers!==null&&!Array.isArray(config.headers)&&Object.values(config.headers).every(headerValue=>typeof headerValue=="string"&&headerValue.length>0))){diagnostics.push(`MCP server "${name}" in ${path15} requires "headers" to be an object with non-empty string values; ignoring it.`);continue}}servers.set(name,{args:config.args??[],deferredTools:config.deferredTools===!0?!0:void 0,...hasCommand?{command:config.command}:{url:config.url,...config.headers===void 0?{}:{headers:config.headers}}})}return{servers,diagnostics}}var MCP_POOL_BRIDGE_SOURCE=`// Generated by the suite MCP registration pool (agent-session-services). Do not edit.
|
|
1069
1069
|
import { spawn } from 'node:child_process';
|
|
1070
1070
|
import { existsSync } from 'node:fs';
|
|
1071
1071
|
import { join } from 'node:path';
|