@ai-agent-forge/agent-forge 0.85.10 → 0.85.12

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.
@@ -273,7 +273,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
273
273
  `:`
274
274
  `)+postfix,endIndex=index3+1,index3=string.indexOf(`
275
275
  `,endIndex)}while(index3!==-1);return returnValue+=string.slice(endIndex),returnValue}var{stdout:stdoutColor,stderr:stderrColor}=supports_color_default,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles2=Object.create(null),applyOptions=(object,options={})=>{if(options.level&&!(Number.isInteger(options.level)&&options.level>=0&&options.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let colorLevel=stdoutColor?stdoutColor.level:0;object.level=options.level===void 0?colorLevel:options.level};var chalkFactory=options=>{let chalk2=(...strings)=>strings.join(" ");return applyOptions(chalk2,options),Object.setPrototypeOf(chalk2,createChalk.prototype),chalk2};function createChalk(options){return chalkFactory(options)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default))styles2[styleName]={get(){let builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,styleName,{value:builder}),builder}};styles2.visible={get(){let builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};var getModelAnsi=(model,level,type,...arguments_)=>model==="rgb"?level==="ansi16m"?ansi_styles_default[type].ansi16m(...arguments_):level==="ansi256"?ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_)):ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_)):model==="hex"?getModelAnsi("rgb",level,type,...ansi_styles_default.hexToRgb(...arguments_)):ansi_styles_default[type][model](...arguments_),usedModels=["rgb","hex","ansi256"];for(let model of usedModels){styles2[model]={get(){let{level}=this;return function(...arguments_){let styler=createStyler(getModelAnsi(model,levelMapping[level],"color",...arguments_),ansi_styles_default.color.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}};let bgModel="bg"+model[0].toUpperCase()+model.slice(1);styles2[bgModel]={get(){let{level}=this;return function(...arguments_){let styler=createStyler(getModelAnsi(model,levelMapping[level],"bgColor",...arguments_),ansi_styles_default.bgColor.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}}}var proto=Object.defineProperties(()=>{},{...styles2,level:{enumerable:!0,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}}),createStyler=(open5,close,parent)=>{let openAll,closeAll;return parent===void 0?(openAll=open5,closeAll=close):(openAll=parent.openAll+open5,closeAll=close+parent.closeAll),{open:open5,close,openAll,closeAll,parent}},createBuilder=(self,_styler,_isEmpty)=>{let builder=(...arguments_)=>applyStyle(builder,arguments_.length===1?""+arguments_[0]:arguments_.join(" "));return Object.setPrototypeOf(builder,proto),builder[GENERATOR]=self,builder[STYLER]=_styler,builder[IS_EMPTY]=_isEmpty,builder},applyStyle=(self,string)=>{if(self.level<=0||!string)return self[IS_EMPTY]?"":string;let styler=self[STYLER];if(styler===void 0)return string;let{openAll,closeAll}=styler;if(string.includes("\x1B"))for(;styler!==void 0;)string=stringReplaceAll(string,styler.close,styler.open),styler=styler.parent;let lfIndex=string.indexOf(`
276
- `);return lfIndex!==-1&&(string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex)),openAll+string+closeAll};Object.defineProperties(createChalk.prototype,styles2);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"],VALID_LOG_LEVELS=["debug","info","warn","error"];function isValidHostLogLevel(level){return VALID_LOG_LEVELS.includes(level)}function isValidTraceKind(kind){return TRACE_KINDS_V1.includes(kind)}var MAX_PLUGIN_CLI_ID_CHARS=128,MAX_PLUGIN_CLI_IDS=128;function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseBoundedPluginId(args,index3,result,option,values){let raw=args[index3+1];if(raw===void 0||raw.startsWith("-"))return result.diagnostics.push({type:"error",message:`${option} requires a plugin id`}),index3;let value=raw.trim();return value.length===0?(result.diagnostics.push({type:"error",message:`${option} requires a non-empty plugin id`}),index3+1):value.length>MAX_PLUGIN_CLI_ID_CHARS?(result.diagnostics.push({type:"error",message:`${option} plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}),index3+1):values.length>=MAX_PLUGIN_CLI_IDS?(result.diagnostics.push({type:"error",message:`${option} accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}),index3+1):(values.push(value),index3+1)}function parsePluginProfileValue(args,index3,result,rawValue){let raw=rawValue??args[index3+1];if(raw===void 0||raw.startsWith("-"))return result.diagnostics.push({type:"error",message:"--plugin-profile requires a profile id"}),index3;let value=raw.trim();return value.length===0?(result.diagnostics.push({type:"error",message:"--plugin-profile requires a non-empty profile id"}),rawValue===void 0?index3+1:index3):value.length>MAX_PLUGIN_CLI_ID_CHARS?(result.diagnostics.push({type:"error",message:`--plugin-profile id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}),rawValue===void 0?index3+1:index3):(result.pluginProfile=value,rawValue===void 0?index3+1:index3)}function parseArgs(args){let result={messages:[],fileArgs:[],diagnostics:[]};for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"&&i+1<args.length){let mode=args[++i];(mode==="text"||mode==="json"||mode==="rpc")&&(result.mode=mode)}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length)result.provider=args[++i];else if((arg==="--model"||arg==="-m")&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--suite"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suite=id,i++):result.diagnostics.push({type:"error",message:"--suite requires a suite id"})}else if(arg==="--suite-create"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteCreate=id,i++):result.diagnostics.push({type:"error",message:"--suite-create requires a suite id"})}else if(arg==="--clone-from"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.cloneFrom=id,i++):result.diagnostics.push({type:"error",message:"--clone-from requires a suite id"})}else if(arg==="--suite-delete"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteDelete=id,i++):result.diagnostics.push({type:"error",message:"--suite-delete requires a suite id"})}else if(arg==="--suite-reset"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteReset=id,i++):result.diagnostics.push({type:"error",message:"--suite-reset requires a suite id"})}else if(arg==="--serve"){let raw=args[i+1],port=raw!==void 0&&/^\d+$/.test(raw)?Number(raw):Number.NaN;Number.isInteger(port)&&port<=65535?(result.serve=port,i++):(result.diagnostics.push({type:"error",message:"--serve requires a valid TCP port (0-65535)"}),raw!==void 0&&i++)}else if(arg==="--subagent-runner")result.subagentRunner=!0;else if(arg==="--serve-workspace-root"){let dir=args[i+1];dir===void 0||dir.startsWith("-")?result.diagnostics.push({type:"error",message:"--serve-workspace-root requires a directory"}):(result.serveWorkspaceRoots=result.serveWorkspaceRoots??[],result.serveWorkspaceRoots.push(dir),i++)}else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if(arg==="--trace"){let next=args[i+1];next!==void 0&&!next.startsWith("-")?(result.trace=next,i++):result.trace=""}else if(arg==="--trace-json")result.traceJson=!0;else if(arg==="--trace-kind"){let raw=args[i+1];if(raw===void 0||raw.startsWith("-"))result.diagnostics.push({type:"error",message:"--trace-kind requires a comma-separated kind list"});else{i++;let kinds=raw.split(",").map(kind=>kind.trim()).filter(kind=>kind.length>0),invalid2=kinds.filter(kind=>!isValidTraceKind(kind));kinds.length===0?result.diagnostics.push({type:"error",message:"--trace-kind requires at least one trace kind"}):invalid2.length>0?result.diagnostics.push({type:"error",message:`Invalid trace kind(s) "${invalid2.join(", ")}". Valid values: ${TRACE_KINDS_V1.join(", ")}`}):result.traceKind=kinds}}else if(arg==="--trace-limit"){let raw=args[i+1];if(raw===void 0||raw.startsWith("-"))result.diagnostics.push({type:"error",message:"--trace-limit requires a positive integer"});else{i++;let limit=/^\d+$/.test(raw)?Number(raw):Number.NaN;Number.isInteger(limit)&&limit>0?result.traceLimit=limit:result.diagnostics.push({type:"error",message:`Invalid trace limit "${raw}". Expected a positive integer`})}}else if(arg==="--no-plugins"||arg==="-np")result.noPlugins=!0;else if(arg==="--no-trace")result.noTrace=!0;else if(arg==="--log-level"){let level=args[i+1];level===void 0||level.startsWith("-")?result.diagnostics.push({type:"error",message:"--log-level requires a level"}):isValidHostLogLevel(level)?(result.logLevel=level,i++):(i++,result.diagnostics.push({type:"error",message:`Invalid log level "${level}". Valid values: ${VALID_LOG_LEVELS.join(", ")}`}))}else if(arg==="--plugin-profile")i=parsePluginProfileValue(args,i,result);else if(arg.startsWith("--plugin-profile="))parsePluginProfileValue(args,i,result,arg.slice(17));else if(arg==="--plugin-scope"||arg.startsWith("--plugin-scope=")){let raw=arg==="--plugin-scope"?args[i+1]:arg.slice(15);arg==="--plugin-scope"&&i++,raw!=="global"&&raw!=="project"?result.diagnostics.push({type:"error",message:"--plugin-scope must be global or project"}):result.pluginSelectionScope!==void 0?result.diagnostics.push({type:"error",message:"--plugin-scope may be specified only once"}):result.pluginSelectionScope=raw}else if(arg==="--plugin")result.plugins=result.plugins??[],i=parseBoundedPluginId(args,i,result,"--plugin",result.plugins);else if(arg.startsWith("--plugin=")){result.plugins=result.plugins??[];let value=arg.slice(9).trim();value.length===0?result.diagnostics.push({type:"error",message:"--plugin requires a non-empty plugin id"}):value.length>MAX_PLUGIN_CLI_ID_CHARS?result.diagnostics.push({type:"error",message:`--plugin plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}):result.plugins.length>=MAX_PLUGIN_CLI_IDS?result.diagnostics.push({type:"error",message:`--plugin accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}):result.plugins.push(value)}else if(arg==="--disable-plugin")result.disabledPlugins=result.disabledPlugins??[],i=parseBoundedPluginId(args,i,result,"--disable-plugin",result.disabledPlugins);else if(arg.startsWith("--disable-plugin=")){result.disabledPlugins=result.disabledPlugins??[];let value=arg.slice(17).trim();value.length===0?result.diagnostics.push({type:"error",message:"--disable-plugin requires a non-empty plugin id"}):value.length>MAX_PLUGIN_CLI_ID_CHARS?result.diagnostics.push({type:"error",message:`--disable-plugin plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}):result.disabledPlugins.length>=MAX_PLUGIN_CLI_IDS?result.diagnostics.push({type:"error",message:`--disable-plugin accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}):result.disabledPlugins.push(value)}else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else arg==="--verbose"?result.verbose=!0:arg==="--offline"?result.offline=!0:arg.startsWith("@")?result.fileArgs.push(arg.slice(1)):arg.startsWith("--")?(result.diagnostics.push({type:"error",message:`Unknown option: ${arg.split("=")[0]}`}),i++):arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||result.messages.push(arg)}return result}function printHelp(){console.log(`${source_default.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools
276
+ `);return lfIndex!==-1&&(string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex)),openAll+string+closeAll};Object.defineProperties(createChalk.prototype,styles2);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"],VALID_LOG_LEVELS=["debug","info","warn","error"];function isValidHostLogLevel(level){return VALID_LOG_LEVELS.includes(level)}function isValidTraceKind(kind){return TRACE_KINDS_V1.includes(kind)}var MAX_PLUGIN_CLI_ID_CHARS=128,MAX_PLUGIN_CLI_IDS=128;function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseBoundedPluginId(args,index3,result,option,values){let raw=args[index3+1];if(raw===void 0||raw.startsWith("-"))return result.diagnostics.push({type:"error",message:`${option} requires a plugin id`}),index3;let value=raw.trim();return value.length===0?(result.diagnostics.push({type:"error",message:`${option} requires a non-empty plugin id`}),index3+1):value.length>MAX_PLUGIN_CLI_ID_CHARS?(result.diagnostics.push({type:"error",message:`${option} plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}),index3+1):values.length>=MAX_PLUGIN_CLI_IDS?(result.diagnostics.push({type:"error",message:`${option} accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}),index3+1):(values.push(value),index3+1)}function parsePluginProfileValue(args,index3,result,rawValue){let raw=rawValue??args[index3+1];if(raw===void 0||raw.startsWith("-"))return result.diagnostics.push({type:"error",message:"--plugin-profile requires a profile id"}),index3;let value=raw.trim();return value.length===0?(result.diagnostics.push({type:"error",message:"--plugin-profile requires a non-empty profile id"}),rawValue===void 0?index3+1:index3):value.length>MAX_PLUGIN_CLI_ID_CHARS?(result.diagnostics.push({type:"error",message:`--plugin-profile id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}),rawValue===void 0?index3+1:index3):(result.pluginProfile=value,rawValue===void 0?index3+1:index3)}function parseArgs(args){let result={messages:[],fileArgs:[],diagnostics:[]};for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"&&i+1<args.length){let mode=args[++i];(mode==="text"||mode==="json"||mode==="rpc")&&(result.mode=mode)}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length)result.provider=args[++i];else if((arg==="--model"||arg==="-m")&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--rebind-suite")result.rebindSuite=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--suite"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suite=id,i++):result.diagnostics.push({type:"error",message:"--suite requires a suite id"})}else if(arg==="--suite-create"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteCreate=id,i++):result.diagnostics.push({type:"error",message:"--suite-create requires a suite id"})}else if(arg==="--clone-from"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.cloneFrom=id,i++):result.diagnostics.push({type:"error",message:"--clone-from requires a suite id"})}else if(arg==="--suite-delete"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteDelete=id,i++):result.diagnostics.push({type:"error",message:"--suite-delete requires a suite id"})}else if(arg==="--suite-reset"){let id=args[i+1];id!==void 0&&!id.startsWith("-")?(result.suiteReset=id,i++):result.diagnostics.push({type:"error",message:"--suite-reset requires a suite id"})}else if(arg==="--serve"){let raw=args[i+1],port=raw!==void 0&&/^\d+$/.test(raw)?Number(raw):Number.NaN;Number.isInteger(port)&&port<=65535?(result.serve=port,i++):(result.diagnostics.push({type:"error",message:"--serve requires a valid TCP port (0-65535)"}),raw!==void 0&&i++)}else if(arg==="--subagent-runner")result.subagentRunner=!0;else if(arg==="--serve-workspace-root"){let dir=args[i+1];dir===void 0||dir.startsWith("-")?result.diagnostics.push({type:"error",message:"--serve-workspace-root requires a directory"}):(result.serveWorkspaceRoots=result.serveWorkspaceRoots??[],result.serveWorkspaceRoots.push(dir),i++)}else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if(arg==="--trace"){let next=args[i+1];next!==void 0&&!next.startsWith("-")?(result.trace=next,i++):result.trace=""}else if(arg==="--trace-json")result.traceJson=!0;else if(arg==="--trace-kind"){let raw=args[i+1];if(raw===void 0||raw.startsWith("-"))result.diagnostics.push({type:"error",message:"--trace-kind requires a comma-separated kind list"});else{i++;let kinds=raw.split(",").map(kind=>kind.trim()).filter(kind=>kind.length>0),invalid2=kinds.filter(kind=>!isValidTraceKind(kind));kinds.length===0?result.diagnostics.push({type:"error",message:"--trace-kind requires at least one trace kind"}):invalid2.length>0?result.diagnostics.push({type:"error",message:`Invalid trace kind(s) "${invalid2.join(", ")}". Valid values: ${TRACE_KINDS_V1.join(", ")}`}):result.traceKind=kinds}}else if(arg==="--trace-limit"){let raw=args[i+1];if(raw===void 0||raw.startsWith("-"))result.diagnostics.push({type:"error",message:"--trace-limit requires a positive integer"});else{i++;let limit=/^\d+$/.test(raw)?Number(raw):Number.NaN;Number.isInteger(limit)&&limit>0?result.traceLimit=limit:result.diagnostics.push({type:"error",message:`Invalid trace limit "${raw}". Expected a positive integer`})}}else if(arg==="--no-plugins"||arg==="-np")result.noPlugins=!0;else if(arg==="--no-trace")result.noTrace=!0;else if(arg==="--log-level"){let level=args[i+1];level===void 0||level.startsWith("-")?result.diagnostics.push({type:"error",message:"--log-level requires a level"}):isValidHostLogLevel(level)?(result.logLevel=level,i++):(i++,result.diagnostics.push({type:"error",message:`Invalid log level "${level}". Valid values: ${VALID_LOG_LEVELS.join(", ")}`}))}else if(arg==="--plugin-profile")i=parsePluginProfileValue(args,i,result);else if(arg.startsWith("--plugin-profile="))parsePluginProfileValue(args,i,result,arg.slice(17));else if(arg==="--plugin-scope"||arg.startsWith("--plugin-scope=")){let raw=arg==="--plugin-scope"?args[i+1]:arg.slice(15);arg==="--plugin-scope"&&i++,raw!=="global"&&raw!=="project"?result.diagnostics.push({type:"error",message:"--plugin-scope must be global or project"}):result.pluginSelectionScope!==void 0?result.diagnostics.push({type:"error",message:"--plugin-scope may be specified only once"}):result.pluginSelectionScope=raw}else if(arg==="--plugin")result.plugins=result.plugins??[],i=parseBoundedPluginId(args,i,result,"--plugin",result.plugins);else if(arg.startsWith("--plugin=")){result.plugins=result.plugins??[];let value=arg.slice(9).trim();value.length===0?result.diagnostics.push({type:"error",message:"--plugin requires a non-empty plugin id"}):value.length>MAX_PLUGIN_CLI_ID_CHARS?result.diagnostics.push({type:"error",message:`--plugin plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}):result.plugins.length>=MAX_PLUGIN_CLI_IDS?result.diagnostics.push({type:"error",message:`--plugin accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}):result.plugins.push(value)}else if(arg==="--disable-plugin")result.disabledPlugins=result.disabledPlugins??[],i=parseBoundedPluginId(args,i,result,"--disable-plugin",result.disabledPlugins);else if(arg.startsWith("--disable-plugin=")){result.disabledPlugins=result.disabledPlugins??[];let value=arg.slice(17).trim();value.length===0?result.diagnostics.push({type:"error",message:"--disable-plugin requires a non-empty plugin id"}):value.length>MAX_PLUGIN_CLI_ID_CHARS?result.diagnostics.push({type:"error",message:`--disable-plugin plugin id must be at most ${MAX_PLUGIN_CLI_ID_CHARS} characters`}):result.disabledPlugins.length>=MAX_PLUGIN_CLI_IDS?result.diagnostics.push({type:"error",message:`--disable-plugin accepts at most ${MAX_PLUGIN_CLI_IDS} plugin ids`}):result.disabledPlugins.push(value)}else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else arg==="--verbose"?result.verbose=!0:arg==="--offline"?result.offline=!0:arg.startsWith("@")?result.fileArgs.push(arg.slice(1)):arg.startsWith("--")?(result.diagnostics.push({type:"error",message:`Unknown option: ${arg.split("=")[0]}`}),i++):arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||result.messages.push(arg)}return result}function printHelp(){console.log(`${source_default.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools
277
277
 
278
278
  ${source_default.bold("Usage:")}
279
279
  ${APP_NAME} [options] [--] [@files...] [messages...]
@@ -1052,7 +1052,7 @@ ${body}
1052
1052
  </skill>`;return args?`${skillBlock}
1053
1053
 
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
- `),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},workspaceDirectory:this._cwd,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,`*
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},workspaceDirectory:this._cwd,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;let providerBaseUrl=result.auth.baseUrl??this._modelRuntime.getProvider(providerId)?.baseUrl;return{...result.auth.apiKey===void 0?{}:{apiKey:result.auth.apiKey},headers:{...result.auth.headers??{}},...providerBaseUrl===void 0?{}:{baseUrl:providerBaseUrl},...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
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)&&current!==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}
@@ -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){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.
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&&!options.allowSuiteRebind){if(sessionSuiteBinding.suiteId!==suiteId)throw new SuiteRebindError(`Session is bound to suite "${sessionSuiteBinding.suiteId}" and cannot resume with "${suiteId}"; rerun with --rebind-suite to adopt the new suite, or create a new session`);if(sessionSuiteBinding.profileIdentity!==void 0&&!profileIdentitiesCompatible(sessionSuiteBinding.profileIdentity,suiteWorkspace.identity))throw new SuiteRebindError("Session Profile identity drift detected (the active plugin set changed since the conversation started); rerun with --rebind-suite to adopt the new plugin set, or create a new session")}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||options.allowSuiteRebind)&&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';
@@ -1487,7 +1487,7 @@ Auth commands require at least one of --provider or --model. Checks refresh expi
1487
1487
  ${content}
1488
1488
  </file>
1489
1489
  `}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: Could not read file ${absolutePath}: ${message}`)),process.exit(1)}}return{text,images}}function buildInitialMessage({parsed,fileText,fileImages,stdinContent}){let parts=[];return stdinContent!==void 0&&parts.push(stdinContent),fileText&&parts.push(fileText),parsed.messages.length>0&&(parts.push(parsed.messages[0]),parsed.messages.shift()),{initialMessage:parts.length>0?parts.join(""):void 0,initialImages:fileImages&&fileImages.length>0?fileImages:void 0}}function formatTokenCount(count){if(count>=1e6){let millions=count/1e6;return millions%1===0?`${millions}M`:`${millions.toFixed(1)}M`}if(count>=1e3){let thousands=count/1e3;return thousands%1===0?`${thousands}K`:`${thousands.toFixed(1)}K`}return count.toString()}async function listModels(modelRuntime,searchPattern,signal){let loadError=modelRuntime.getError();loadError&&console.error(source_default.yellow(`Warning: errors loading models.json:
1490
- ${loadError}`));let models=[...await modelRuntime.getAvailable(void 0,{signal})];if(models.length===0){console.log(formatNoModelsAvailableMessage());return}let filteredModels=models;if(searchPattern&&(filteredModels=fuzzyFilter(models,searchPattern,m2=>`${m2.provider} ${m2.id}`)),filteredModels.length===0){console.log(`No models matching "${searchPattern}"`);return}filteredModels.sort((a,b2)=>{let providerCmp=a.provider.localeCompare(b2.provider);return providerCmp!==0?providerCmp:a.id.localeCompare(b2.id)});let rows=filteredModels.map(m2=>({provider:m2.provider,model:m2.id,context:formatTokenCount(m2.contextWindow),maxOut:formatTokenCount(m2.maxTokens),thinking:m2.reasoning?"yes":"no",images:m2.input.includes("image")?"yes":"no"})),headers={provider:"provider",model:"model",context:"context",maxOut:"max-out",thinking:"thinking",images:"images"},widths={provider:Math.max(headers.provider.length,...rows.map(r=>r.provider.length)),model:Math.max(headers.model.length,...rows.map(r=>r.model.length)),context:Math.max(headers.context.length,...rows.map(r=>r.context.length)),maxOut:Math.max(headers.maxOut.length,...rows.map(r=>r.maxOut.length)),thinking:Math.max(headers.thinking.length,...rows.map(r=>r.thinking.length)),images:Math.max(headers.images.length,...rows.map(r=>r.images.length))},headerLine=[headers.provider.padEnd(widths.provider),headers.model.padEnd(widths.model),headers.context.padEnd(widths.context),headers.maxOut.padEnd(widths.maxOut),headers.thinking.padEnd(widths.thinking),headers.images.padEnd(widths.images)].join(" ");console.log(headerLine);for(let row of rows){let line=[row.provider.padEnd(widths.provider),row.model.padEnd(widths.model),row.context.padEnd(widths.context),row.maxOut.padEnd(widths.maxOut),row.thinking.padEnd(widths.thinking),row.images.padEnd(widths.images)].join(" ");console.log(line)}}import{join as join59}from"node:path";var FACTORY_PLUGIN_RANGE=`^${VERSION}`,BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1=Object.freeze([{pluginId:"agent-forge.plugin.goal",npmName:"@ai-agent-forge/plugin-goal",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.plan",npmName:"@ai-agent-forge/plugin-plan",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.todo-set",npmName:"@ai-agent-forge/plugin-todo-set",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.session-share",npmName:"@ai-agent-forge/plugin-session-share",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.observability",npmName:"@ai-agent-forge/plugin-observability",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.subagent-delegate",npmName:"@ai-agent-forge/plugin-subagent-delegate",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.memory",npmName:"@ai-agent-forge/plugin-memory",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.image-generation",npmName:"@ai-agent-forge/plugin-image-generation",range:FACTORY_PLUGIN_RANGE}]);function printResponse(response2,write){write(response2.text),response2.status!=="succeeded"&&(process.exitCode=1)}function buildMarketCli(options){let{market,overrides}=options;return createPluginEcosystemCliV1({host:overrides?.host??defaultPluginHostFactsV1(),manifests:listBuiltinPluginManifestsV1(),registry:overrides?.registry??market?.cliRegistry,...overrides?.acquisition===void 0&&market?.acquisition===void 0?{}:{acquisition:overrides?.acquisition??market?.acquisition},installer:overrides?.installer??market?.installer,...overrides?.distribution!==void 0||market?.distribution!==void 0?{distribution:overrides?.distribution??market.distribution}:{},stateStore:overrides?.stateStore??market?.stateStore??createPluginStateStoreV1({filePath:join59(options.agentDir,"plugin-state.json")}),projectStateStore:overrides?.projectStateStore??market?.projectStateStore??createPluginStateStoreV1({filePath:join59(options.cwd,CONFIG_DIR_NAME,"plugin-state.json")}),projectScopeRef:projectPluginScopeRefV1(options.cwd),selectionStore:overrides?.selectionStore??createPluginSelectionStoreV1({filePath:join59(options.agentDir,".plugin-selection.json")}),projectSelectionStore:overrides?.projectSelectionStore??createPluginSelectionStoreV1({filePath:join59(options.cwd,CONFIG_DIR_NAME,".plugin-selection.json")})})}async function createDefaultPluginManagerControllerV1(options){let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),market=await createDefaultPluginMarketWiringV1({agentDir,cwd}),cli=buildMarketCli({agentDir,cwd,market});return{controller:createPluginManagerControllerV1({registry:market.registry,stateStore:options.scope==="project"?market.projectStateStore:market.stateStore,cli}),close:market.close}}async function handlePluginEcosystemCommand(args,options={}){if(args[0]!=="plugin")return!1;let write=options.write??(line=>console.log(line));if(args[1]==="update"&&args[2]==="--all")return await runBatchUpdate(args.slice(3),options,write),!0;let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),market=options.registry===void 0&&options.installer===void 0?await createDefaultPluginMarketWiringV1({agentDir,cwd}):void 0;try{let response2=await buildMarketCli({agentDir,cwd,market,overrides:options}).execute({argv:args.slice(1)});return printResponse(response2,write),!0}finally{await market?.close()}}async function runBatchUpdate(restArgs,options,write){let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),scopeIndex=restArgs.indexOf("--scope"),scope=scopeIndex!==-1&&restArgs[scopeIndex+1]==="project"?"project":"global",market=options.registry===void 0&&options.installer===void 0?await createDefaultPluginMarketWiringV1({agentDir,cwd}):void 0;try{let cli=buildMarketCli({agentDir,cwd,market,overrides:options}),listResponse=await cli.execute({argv:["state","list","--scope",scope]});if(listResponse.status!=="succeeded"){printResponse(listResponse,write);return}let entries=(listResponse.data?.entries??[]).filter(entry=>entry.lifecycle==="active"&&entry.scope===scope);if(entries.length===0){write("No active plugins to update.");return}let updated=[],current=[],failed=[];for(let entry of entries){let factoryEntry=BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1.find(item=>item.pluginId===entry.pluginId),argv=factoryEntry?["install",`${factoryEntry.npmName}@${factoryEntry.range??"latest"}`,"--scope",scope]:["update",entry.pluginId,"--scope",scope],response2=await cli.execute({argv});response2.status==="succeeded"?(updated.push(entry.pluginId),write(response2.text)):response2.error?.code==="already_installed"?current.push(entry.pluginId):(failed.push(entry.pluginId),write(response2.text))}let summary=[`updated ${updated.length}${updated.length>0?` (${updated.join(", ")})`:""}`,`already up to date ${current.length}${current.length>0?` (${current.join(", ")})`:""}`,`failed ${failed.length}${failed.length>0?` (${failed.join(", ")})`:""}`].join("; ");write(`plugin update --all [${scope}]: ${summary}`),failed.length>0&&(process.exitCode=1)}finally{await market?.close()}}import{join as join60}from"node:path";var DEFAULT_DURABLE_LOG_RELATIVE_PATH=join60("durable","remote-server-ops.jsonl");function isAddrInUse(error2){return typeof error2=="object"&&error2!==null&&error2.code==="EADDRINUSE"}async function runServeMode(port,options){let handle,createListener=options?.createListener??(()=>createWsServerListener({port,httpRequestHandler:(request,response2)=>handle?.server.handleArtifactHttpRequest(request,response2)??!1,onError:error2=>{console.error(`remote-server error: ${error2.message}`)}})),startServer=options?.startServer??startCodingAgentRemoteServer,workspaceRoots=options?.workspaceRoots,sessionDir=options?.sessionDir,durable=options?.durable??createDurableService({backend:createFileDurableStoreBackend({path:join60(getAgentDir(),DEFAULT_DURABLE_LOG_RELATIVE_PATH)})}),writerId=readOrCreateWriterId(getAgentDir());try{handle=await startServer({sessionSourceOptions:{sessionsDir:sessionDir??getSessionsDir(),cwd:process.cwd(),agentDir:getAgentDir(),...workspaceRoots===void 0||workspaceRoots.length===0?{}:{workspaceRoots},agentTaskResults:{store:durable,writerId},subagentPoolFromSelfInvocation:!0,...options?.hostLogger===void 0?{}:{hostLogger:options.hostLogger}},listeners:[createListener()],onError:error2=>{console.error(`remote-server error: ${error2.message}`)},durable,writerId})}catch(error2){throw isAddrInUse(error2)&&(console.error(`Port ${port} is already in use`),process.exit(1)),error2}let closing=!1,shutdown=()=>{closing||(closing=!0,handle.close().then(()=>{process.exit(0)}).catch(error2=>{console.error(`Remote server shutdown failed: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}))};process.on("SIGINT",shutdown),process.on("SIGTERM",shutdown),console.log(`Remote server listening on ${handle.addresses.join(", ")}`)}import{existsSync as existsSync29}from"fs";var THEME_OPTIONS=[{value:"dark",label:"Dark"},{value:"light",label:"Light"}],ANALYTICS_OPTIONS=[{value:!0,label:"Share anonymous usage data"},{value:!1,label:"Don't share"}],SETUP_LOGO_LINES=["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588"],FirstTimeSetupComponent=class extends Container{step="theme";themeIndex;analyticsIndex=0;options;constructor(options){super(),this.options=options,this.themeIndex=Math.max(0,THEME_OPTIONS.findIndex(option=>option.value===options.detectedTheme)),this.update()}update(){this.clear(),this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",SETUP_LOGO_LINES.join(`
1490
+ ${loadError}`));let models=[...await modelRuntime.getAvailable(void 0,{signal})];if(models.length===0){console.log(formatNoModelsAvailableMessage());return}let filteredModels=models;if(searchPattern&&(filteredModels=fuzzyFilter(models,searchPattern,m2=>`${m2.provider} ${m2.id}`)),filteredModels.length===0){console.log(`No models matching "${searchPattern}"`);return}filteredModels.sort((a,b2)=>{let providerCmp=a.provider.localeCompare(b2.provider);return providerCmp!==0?providerCmp:a.id.localeCompare(b2.id)});let rows=filteredModels.map(m2=>({provider:m2.provider,model:m2.id,context:formatTokenCount(m2.contextWindow),maxOut:formatTokenCount(m2.maxTokens),thinking:m2.reasoning?"yes":"no",images:m2.input.includes("image")?"yes":"no"})),headers={provider:"provider",model:"model",context:"context",maxOut:"max-out",thinking:"thinking",images:"images"},widths={provider:Math.max(headers.provider.length,...rows.map(r=>r.provider.length)),model:Math.max(headers.model.length,...rows.map(r=>r.model.length)),context:Math.max(headers.context.length,...rows.map(r=>r.context.length)),maxOut:Math.max(headers.maxOut.length,...rows.map(r=>r.maxOut.length)),thinking:Math.max(headers.thinking.length,...rows.map(r=>r.thinking.length)),images:Math.max(headers.images.length,...rows.map(r=>r.images.length))},headerLine=[headers.provider.padEnd(widths.provider),headers.model.padEnd(widths.model),headers.context.padEnd(widths.context),headers.maxOut.padEnd(widths.maxOut),headers.thinking.padEnd(widths.thinking),headers.images.padEnd(widths.images)].join(" ");console.log(headerLine);for(let row of rows){let line=[row.provider.padEnd(widths.provider),row.model.padEnd(widths.model),row.context.padEnd(widths.context),row.maxOut.padEnd(widths.maxOut),row.thinking.padEnd(widths.thinking),row.images.padEnd(widths.images)].join(" ");console.log(line)}}import{join as join59}from"node:path";var FACTORY_PLUGIN_RANGE=`^${VERSION}`,BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1=Object.freeze([{pluginId:"agent-forge.plugin.goal",npmName:"@ai-agent-forge/plugin-goal",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.plan",npmName:"@ai-agent-forge/plugin-plan",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.todo-set",npmName:"@ai-agent-forge/plugin-todo-set",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.session-share",npmName:"@ai-agent-forge/plugin-session-share",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.observability",npmName:"@ai-agent-forge/plugin-observability",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.subagent-delegate",npmName:"@ai-agent-forge/plugin-subagent-delegate",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.memory",npmName:"@ai-agent-forge/plugin-memory",range:FACTORY_PLUGIN_RANGE},{pluginId:"agent-forge.plugin.image-generation",npmName:"@ai-agent-forge/plugin-image-generation",range:FACTORY_PLUGIN_RANGE}]);function printResponse(response2,write){write(response2.text),response2.status!=="succeeded"&&(process.exitCode=1)}function buildMarketCli(options){let{market,overrides}=options;return createPluginEcosystemCliV1({host:overrides?.host??defaultPluginHostFactsV1(),manifests:listBuiltinPluginManifestsV1(),registry:overrides?.registry??market?.cliRegistry,...overrides?.acquisition===void 0&&market?.acquisition===void 0?{}:{acquisition:overrides?.acquisition??market?.acquisition},installer:overrides?.installer??market?.installer,...overrides?.distribution!==void 0||market?.distribution!==void 0?{distribution:overrides?.distribution??market.distribution}:{},stateStore:overrides?.stateStore??market?.stateStore??createPluginStateStoreV1({filePath:join59(options.agentDir,"plugin-state.json")}),projectStateStore:overrides?.projectStateStore??market?.projectStateStore??createPluginStateStoreV1({filePath:join59(options.cwd,CONFIG_DIR_NAME,"plugin-state.json")}),projectScopeRef:projectPluginScopeRefV1(options.cwd),selectionStore:overrides?.selectionStore??createPluginSelectionStoreV1({filePath:join59(options.agentDir,".plugin-selection.json")}),projectSelectionStore:overrides?.projectSelectionStore??createPluginSelectionStoreV1({filePath:join59(options.cwd,CONFIG_DIR_NAME,".plugin-selection.json")})})}async function createDefaultPluginManagerControllerV1(options){let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),market=await createDefaultPluginMarketWiringV1({agentDir,cwd}),cli=buildMarketCli({agentDir,cwd,market});return{controller:createPluginManagerControllerV1({registry:market.registry,stateStore:options.scope==="project"?market.projectStateStore:market.stateStore,cli}),close:market.close}}async function handlePluginEcosystemCommand(args,options={}){if(args[0]!=="plugin")return!1;let write=options.write??(line=>console.log(line));if(args[1]==="update"&&args[2]==="--all")return await runBatchUpdate(args.slice(3),options,write),!0;let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),market=options.registry===void 0&&options.installer===void 0?await createDefaultPluginMarketWiringV1({agentDir,cwd}):void 0;try{let response2=await buildMarketCli({agentDir,cwd,market,overrides:options}).execute({argv:args.slice(1)});return printResponse(response2,write),response2.status==="succeeded"&&response2.command==="install"&&write("note: this plugin is installed but not yet selected by a profile; to activate its tools run: agent-forge plugin selection set <profile> <pluginId>"),!0}finally{await market?.close()}}async function runBatchUpdate(restArgs,options,write){let agentDir=options.agentDir??getAgentDir(),cwd=options.cwd??process.cwd(),scopeIndex=restArgs.indexOf("--scope"),scope=scopeIndex!==-1&&restArgs[scopeIndex+1]==="project"?"project":"global",market=options.registry===void 0&&options.installer===void 0?await createDefaultPluginMarketWiringV1({agentDir,cwd}):void 0;try{let cli=buildMarketCli({agentDir,cwd,market,overrides:options}),listResponse=await cli.execute({argv:["state","list","--scope",scope]});if(listResponse.status!=="succeeded"){printResponse(listResponse,write);return}let entries=(listResponse.data?.entries??[]).filter(entry=>entry.lifecycle==="active"&&entry.scope===scope);if(entries.length===0){write("No active plugins to update.");return}let updated=[],current=[],failed=[];for(let entry of entries){let factoryEntry=BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1.find(item=>item.pluginId===entry.pluginId),argv=factoryEntry?["install",`${factoryEntry.npmName}@${factoryEntry.range??"latest"}`,"--scope",scope]:["update",entry.pluginId,"--scope",scope],response2=await cli.execute({argv});response2.status==="succeeded"?(updated.push(entry.pluginId),write(response2.text)):response2.error?.code==="already_installed"?current.push(entry.pluginId):(failed.push(entry.pluginId),write(response2.text))}let summary=[`updated ${updated.length}${updated.length>0?` (${updated.join(", ")})`:""}`,`already up to date ${current.length}${current.length>0?` (${current.join(", ")})`:""}`,`failed ${failed.length}${failed.length>0?` (${failed.join(", ")})`:""}`].join("; ");write(`plugin update --all [${scope}]: ${summary}`),failed.length>0&&(process.exitCode=1)}finally{await market?.close()}}import{join as join60}from"node:path";var DEFAULT_DURABLE_LOG_RELATIVE_PATH=join60("durable","remote-server-ops.jsonl");function isAddrInUse(error2){return typeof error2=="object"&&error2!==null&&error2.code==="EADDRINUSE"}async function runServeMode(port,options){let handle,createListener=options?.createListener??(()=>createWsServerListener({port,httpRequestHandler:(request,response2)=>handle?.server.handleArtifactHttpRequest(request,response2)??!1,onError:error2=>{console.error(`remote-server error: ${error2.message}`)}})),startServer=options?.startServer??startCodingAgentRemoteServer,workspaceRoots=options?.workspaceRoots,sessionDir=options?.sessionDir,durable=options?.durable??createDurableService({backend:createFileDurableStoreBackend({path:join60(getAgentDir(),DEFAULT_DURABLE_LOG_RELATIVE_PATH)})}),writerId=readOrCreateWriterId(getAgentDir());try{handle=await startServer({sessionSourceOptions:{sessionsDir:sessionDir??getSessionsDir(),cwd:process.cwd(),agentDir:getAgentDir(),...workspaceRoots===void 0||workspaceRoots.length===0?{}:{workspaceRoots},agentTaskResults:{store:durable,writerId},subagentPoolFromSelfInvocation:!0,...options?.hostLogger===void 0?{}:{hostLogger:options.hostLogger}},listeners:[createListener()],onError:error2=>{console.error(`remote-server error: ${error2.message}`)},durable,writerId})}catch(error2){throw isAddrInUse(error2)&&(console.error(`Port ${port} is already in use`),process.exit(1)),error2}let closing=!1,shutdown=()=>{closing||(closing=!0,handle.close().then(()=>{process.exit(0)}).catch(error2=>{console.error(`Remote server shutdown failed: ${error2 instanceof Error?error2.message:String(error2)}`),process.exit(1)}))};process.on("SIGINT",shutdown),process.on("SIGTERM",shutdown),console.log(`Remote server listening on ${handle.addresses.join(", ")}`)}import{existsSync as existsSync29}from"fs";var THEME_OPTIONS=[{value:"dark",label:"Dark"},{value:"light",label:"Light"}],ANALYTICS_OPTIONS=[{value:!0,label:"Share anonymous usage data"},{value:!1,label:"Don't share"}],SETUP_LOGO_LINES=["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588"],FirstTimeSetupComponent=class extends Container{step="theme";themeIndex;analyticsIndex=0;options;constructor(options){super(),this.options=options,this.themeIndex=Math.max(0,THEME_OPTIONS.findIndex(option=>option.value===options.detectedTheme)),this.update()}update(){this.clear(),this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",SETUP_LOGO_LINES.join(`
1491
1491
  `)),1,0)),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",theme.bold(`Welcome to ${APP_NAME}, the minimal coding agent.`)),1,0)),this.addChild(new Spacer(1)),this.step==="theme"?(this.addChild(new Text(theme.fg("text","Pick a theme."),1,0)),this.addChild(new Text(theme.fg("muted",`Detected system appearance: ${this.options.detectedTheme}`),1,0)),this.addChild(new Spacer(1)),this.addOptionList(THEME_OPTIONS.map(option=>option.label),this.themeIndex)):(this.addChild(new Text(theme.fg("text","Opt-in to anonymous usage data sharing?"),1,0)),this.addChild(new Text(theme.fg("muted",`Opting in stores a tracking identifier in settings.json and enables anonymous
1492
1492
  usage analytics. This helps us to better debug, reproduce, and resolve issues
1493
1493
  and bugs within Agent Forge. You can observe what is shared using /privacy and make
@@ -1576,4 +1576,4 @@ Options:
1576
1576
  `));if(command.kind!=="check"){let signal=AbortSignal.timeout(15e3),modelRuntime=await ModelRuntime.create({allowModelNetwork:!1,signal}),credential2=await resolveCredentialForPrint(parsed,modelRuntime,command.kind,command.minExpiryMs,signal);return process.stdout.write(`${credential2}
1577
1577
  `),!0}let requestedAuth=validateAuthCommandArgs(parsed,command.kind),result,credential;try{let credentials=command.noRefresh?new ReadOnlyAuthStorage:AuthStorage.create(),modelRuntime=await createAuthCheckModelRuntime(credentials);result=await checkProviderAuth(parsed,modelRuntime,{refresh:!command.noRefresh}),command.credentials&&result.status==="ready"&&(credential=await getProviderCredential(result.provider,modelRuntime,credentials,{refresh:!command.noRefresh}),credential||(result={status:"not_ready",provider:result.provider,reason:"credential_not_available"}))}catch{result={status:"invalid",provider:requestedAuth.provider??requestedAuth.model,reason:"invalid_state"}}let output=command.json?JSON.stringify({...result,...credential?{credentials:credential}:{}}):credential??result.status;process.stdout.write(`${output}
1578
1578
  `),process.exitCode=result.status==="ready"?0:result.status==="not_ready"?1:2}catch(error2){let message=error2 instanceof AuthCommandError?error2.message:"Failed to resolve credential";console.error(source_default.red(`Error: ${message}`)),process.exitCode=command.kind==="check"?2:1}return!0}async function prepareInitialMessage(parsed,autoResizeImages,stdinContent){if(parsed.fileArgs.length===0)return buildInitialMessage({parsed,stdinContent});let{text,images}=await processFileArguments(parsed.fileArgs,{autoResizeImages});return buildInitialMessage({parsed,fileText:text,fileImages:images,stdinContent})}async function findLocalSessionByExactId(sessionId,cwd,sessionDir){let localMatch=(await SessionManager.list(cwd,sessionDir)).find(s=>s.id===sessionId);return localMatch?{type:"local",path:localMatch.path}:void 0}async function promptConfirm(message){return new Promise(resolve25=>{let rl=createInterface4({input:process.stdin,output:process.stdout});rl.question(`${message} [y/N] `,answer=>{rl.close(),resolve25(answer.toLowerCase()==="y"||answer.toLowerCase()==="yes")})})}function printSuiteLifecycleError(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`))}function suiteWorkspaceExists(agentDir,id){return existsSync34(join68(getSuiteWorkspaceDir(agentDir,id),SUITE_MANIFEST_FILENAME))}async function handleSuiteLifecycleCommands(parsed,cwd,agentDir){if(parsed.suiteCreate!==void 0){try{let result=createSuite({agentDir,id:parsed.suiteCreate,...parsed.cloneFrom===void 0?{}:{cloneFrom:parsed.cloneFrom}});console.log(`Created suite "${result.suiteId}" at ${result.suiteDir}`)}catch(error2){printSuiteLifecycleError(error2),process.exit(1)}process.exit(0)}if(parsed.cloneFrom!==void 0&&(console.error(source_default.red("Error: --clone-from requires --suite-create")),process.exit(1)),parsed.suiteDelete!==void 0){let id=parsed.suiteDelete;isBuiltinSuiteId(id)&&(printSuiteLifecycleError(new SuiteLifecycleError("delete",id,[`builtin suite "${id}" cannot be deleted`])),process.exit(1)),suiteWorkspaceExists(agentDir,id)||(printSuiteLifecycleError(new SuiteResolutionError(id,listSuiteIds(agentDir))),process.exit(1));let refs=findSuiteSessionRefs(agentDir,id);if(refs.length>0){console.error(source_default.red(`Error: suite "${id}" is referenced by ${refs.length} existing session(s); deletion refused:`));for(let ref of refs)console.error(` ${ref.sessionId} ${ref.path}`);process.exit(1)}let suiteDir=getSuiteWorkspaceDir(agentDir,id);console.log(`Deleting suite "${id}": the workspace directory ${suiteDir} will be moved to the trash and released.`),process.stdin.isTTY||(console.error(source_default.red(`Refusing to delete suite "${id}" without an interactive confirmation (non-interactive stdin). Re-run in a terminal to confirm.`)),process.exit(1)),await promptConfirm(`Delete suite "${id}"?`)||(console.log(`Aborted: suite "${id}" was not deleted.`),process.exit(1));try{let result=deleteSuite({agentDir,id,refs}),cleanup=clearDanglingSuiteSettings(SettingsManager.create(cwd,agentDir),id);for(let scope of cleanup.clearedScopes)console.log(`Cleared the ${scope} settings "suite" key (pointed at "${id}").`);releaseTrashedSuite(result.trashPath),console.log(`Deleted suite "${id}"; the workspace was moved to ${result.trashPath} and is being released.`)}catch(error2){printSuiteLifecycleError(error2),process.exit(1)}process.exit(0)}if(parsed.suiteReset!==void 0){let id=parsed.suiteReset;if(!isBuiltinSuiteId(id)){let message=listSuiteIds(agentDir).includes(id)?`Suite "${id}" is a user suite; only builtin suites can be reset \u2014 use --suite-delete instead.`:new SuiteResolutionError(id,listSuiteIds(agentDir)).message;console.error(source_default.red(`Error: ${message}`)),process.exit(1)}try{let plan=resetSuite({agentDir,id});plan.diffText.length===0&&(console.log(`Suite "${id}" already matches the factory contents; nothing to reset.`),process.exit(0)),console.log(`Resetting builtin suite "${id}" to the factory contents:
1579
- `),console.log(plan.diffText),process.stdin.isTTY||(console.error(source_default.red(`Refusing to reset suite "${id}" without an interactive confirmation (non-interactive stdin). Review the diff above and re-run in a terminal to confirm.`)),process.exit(1)),await promptConfirm(`Apply reset of suite "${id}"?`)||(console.log(`Aborted: suite "${id}" was not reset.`),process.exit(1));let result=plan.apply();console.log(`Suite "${id}" was reset to the factory contents (profile lock generation ${result.lock.generation}).`)}catch(error2){printSuiteLifecycleError(error2),process.exit(1)}process.exit(0)}}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}. To resume that exact session, drop the other flags and use --session-id alone (or use --continue to resume the most recent session).`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path15,sessionDir){try{return SessionManager.open(path15,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager){if(parsed.noSession||parsed.help||parsed.listModels!==void 0)return SessionManager.inMemory(cwd,parsed.sessionId!==void 0?{id:parsed.sessionId}:void 0);if(parsed.fork){parsed.sessionId&&await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":return console.log(source_default.yellow(`Session found in different project: ${resolved.cwd}`)),await promptConfirm("Fork this session into current directory?")||(console.log(source_default.dim("Aborted.")),process.exit(0)),forkSessionOrExit(resolved.path,cwd,sessionDir);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let selectedPath=await selectSession(onProgress=>SessionManager.list(cwd,sessionDir,onProgress),onProgress=>SessionManager.listAll(sessionDir,onProgress),settingsManager);return selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0)),SessionManager.open(selectedPath,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue)return SessionManager.continueRecent(cwd,sessionDir);if(parsed.sessionId){let existingSession=await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={},diagnostics=[],cliThinkingFromModel=!1;if(parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error}),resolved.model&&(options.model=resolved.model,!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel)):(options.model=scopedModels[0].model,!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),parsed.suite&&(options.suite=parsed.suite),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}function isBuiltinPluginProfileId(value){return listBuiltinPluginProfilesV1().some(profile=>profile.id===value)}function selectionDiagnostics(status2,diagnostics){return diagnostics.map(item=>({type:"error",message:`Plugin selection ${status2} (${item.code}): ${item.message}`}))}async function resolveCliPluginSelection(parsed,agentDir,cwd){if(!(parsed.pluginProfile!==void 0||parsed.plugins!==void 0||parsed.disabledPlugins!==void 0||parsed.pluginSelectionScope!==void 0)||parsed.noPlugins)return{diagnostics:[]};if(parsed.pluginProfile===void 0&&parsed.plugins===void 0&&parsed.disabledPlugins===void 0)return{diagnostics:[{type:"error",message:"--plugin-scope requires an explicit plugin selection"}]};let diagnostics=[],selectionPath=(parsed.pluginSelectionScope??"global")==="project"?join68(cwd,CONFIG_DIR_NAME,".plugin-selection.json"):join68(agentDir,".plugin-selection.json"),store=createPluginSelectionStoreV1({filePath:selectionPath}),persistedResult;try{persistedResult=await store.read()}catch{return diagnostics.push({type:"error",message:"Plugin selection could not be read"}),{diagnostics}}if(persistedResult.status==="invalid"||persistedResult.status==="cancelled")return diagnostics.push(...selectionDiagnostics(persistedResult.status,persistedResult.diagnostics)),{diagnostics};let explicitProfileId=parsed.pluginProfile,profileId;if(explicitProfileId!==void 0){if(!isBuiltinPluginProfileId(explicitProfileId))return diagnostics.push({type:"error",message:`Unknown plugin profile: ${explicitProfileId}`}),{diagnostics};profileId=explicitProfileId}let persistedSelection2;if(profileId!==void 0)persistedSelection2=persistedResult.snapshot.selections.find(selection=>selection.profileId===profileId);else if(parsed.plugins!==void 0||parsed.disabledPlugins!==void 0){if(persistedResult.snapshot.selections.length!==1)return diagnostics.push({type:"error",message:persistedResult.snapshot.selections.length===0?"--plugin/--disable-plugin requires --plugin-profile or one persisted plugin profile":"--plugin/--disable-plugin requires --plugin-profile when multiple persisted profiles exist"}),{diagnostics};if(persistedSelection2=persistedResult.snapshot.selections[0],persistedSelection2!==void 0&&isBuiltinPluginProfileId(persistedSelection2.profileId))profileId=persistedSelection2.profileId;else return diagnostics.push({type:"error",message:`Unknown persisted plugin profile: ${persistedSelection2?.profileId??""}`}),{diagnostics}}return{...profileId===void 0?{}:{profileId},...parsed.plugins!==void 0?{selectedPluginIds:Object.freeze([...parsed.plugins])}:persistedSelection2===void 0?{}:{selectedPluginIds:persistedSelection2.selectedPluginIds},...parsed.disabledPlugins!==void 0?{disabledPluginIds:Object.freeze([...parsed.disabledPlugins])}:persistedSelection2===void 0?{}:{disabledPluginIds:persistedSelection2.disabledPluginIds},diagnostics}}async function main(args,options){resetTimings();let offlineMode=args.includes("--offline")||isTruthyEnvFlag(process.env.AGENT_FORGE_OFFLINE);if(offlineMode&&(process.env.AGENT_FORGE_OFFLINE="1",process.env.AGENT_FORGE_SKIP_VERSION_CHECK="1"),await runAuthCommand(args)||await handlePluginEcosystemCommand(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getPackageDir()),cleanupManagedInstall();let cwd=process.cwd(),agentDir=getAgentDir(),bootstrapSettingsManager=SettingsManager.create(cwd,agentDir);if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await handlePackageCommand(args)){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;process.exit(exitCode);return}let configCommandOptions=options?.pluginManagerController===void 0&&options?.projectPluginManagerController===void 0?void 0:{...options?.pluginManagerController===void 0?{}:{pluginManagerController:options.pluginManagerController},...options?.projectPluginManagerController===void 0?{}:{projectPluginManagerController:options.projectPluginManagerController}};if(await handleConfigCommand(args,configCommandOptions))return;let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d2 of parsed.diagnostics){let color=d2.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d2.type==="error"?"Error":"Warning"}: ${d2.message}`))}parsed.diagnostics.some(d2=>d2.type==="error")&&process.exit(1)}time("parseArgs");let envLogLevel=process.env.AGENT_FORGE_LOG_LEVEL,hostLogLevel=parsed.logLevel??(envLogLevel!==void 0&&isValidHostLogLevel(envLogLevel)?envLogLevel:void 0),rawLogMaxAgeDays=process.env.AGENT_FORGE_LOG_MAX_AGE_DAYS,hostLogMaxAgeDays=rawLogMaxAgeDays!==void 0&&/^\d+$/.test(rawLogMaxAgeDays)?Number.parseInt(rawLogMaxAgeDays,10):void 0;processHostLogger===void 0&&(processHostLogger=createHostLogger({dir:join68(agentDir,"logs"),...hostLogLevel===void 0?{}:{level:hostLogLevel},...hostLogMaxAgeDays===void 0?{}:{maxAgeDays:hostLogMaxAgeDays}}));let rawTraceMaxAgeDays=process.env.AGENT_FORGE_TRACE_MAX_AGE_DAYS,traceMaxAgeDays=rawTraceMaxAgeDays!==void 0&&/^\d+$/.test(rawTraceMaxAgeDays)?Number.parseInt(rawTraceMaxAgeDays,10):0;if(traceMaxAgeDays>0){let traceSweep=sweepTraceFiles(getSessionsDir(),{maxAgeDays:traceMaxAgeDays,now:Date.now});traceSweep.deleted>0&&processHostLogger.info("retention","trace sweep removed expired trace files",{fields:{deleted:traceSweep.deleted,failed:traceSweep.failed}}),traceSweep.failed>0&&processHostLogger.warn("retention","trace sweep finished with failures",{fields:{deleted:traceSweep.deleted,failed:traceSweep.failed}})}if(parsed.version&&(console.log(VERSION),process.exit(0)),parsed.export){let result;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result=await exportFromFile(parsed.export,outputPath)}catch(error2){let message=error2 instanceof Error?error2.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}console.log(`Exported to: ${result}`),process.exit(0)}if(parsed.trace!==void 0){let envSessionDir2=process.env[ENV_SESSION_DIR],sessionDir2=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir2?expandTildePath(envSessionDir2):void 0)??bootstrapSettingsManager.getSessionDir(),result=await runTraceView(parsed.trace,{json:parsed.traceJson===!0,cwd,...sessionDir2===void 0?{}:{sessionDir:sessionDir2},...parsed.traceKind===void 0?{}:{kinds:parsed.traceKind},...parsed.traceLimit===void 0?{}:{limit:parsed.traceLimit}});result.ok||(console.error(source_default.red(`Error: ${result.message}`)),process.exit(1)),process.exit(0)}if(parsed.serve!==void 0){if(parsed.help||parsed.listModels!==void 0){runMigrations(cwd),reportDiagnostics(collectSettingsDiagnostics(bootstrapSettingsManager)),parsed.help&&(printHelp(),process.exit(0));let modelRuntime2=await ModelRuntime.create({signal:AbortSignal.timeout(15e3)}),searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime2,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let conflictingFlags=[parsed.print?"--print":void 0,parsed.messages.length>0?"positional args":void 0,parsed.fileArgs.length>0?"@file args":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.session?"--session":void 0,parsed.sessionId?"--session-id":void 0,parsed.fork?"--fork":void 0,parsed.noSession?"--no-session":void 0,parsed.mode?"--mode":void 0,parsed.suiteCreate?"--suite-create":void 0,parsed.suiteDelete?"--suite-delete":void 0,parsed.suiteReset?"--suite-reset":void 0,parsed.cloneFrom?"--clone-from":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --serve cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));let ignoredFlags=[["--name",parsed.name!==void 0],["--thinking",parsed.thinking!==void 0],["--provider",parsed.provider!==void 0],["--model",parsed.model!==void 0],["--api-key",parsed.apiKey!==void 0],["--models",(parsed.models?.length??0)>0],["--verbose",parsed.verbose===!0],["--tui-mode",parsed.tuiMode!==void 0],["--suite",parsed.suite!==void 0],["--tools",(parsed.tools?.length??0)>0],["--exclude-tools",(parsed.excludeTools?.length??0)>0],["--no-tools",parsed.noTools===!0],["--no-builtin-tools",parsed.noBuiltinTools===!0],["--skill",(parsed.skills?.length??0)>0],["--prompt-template",(parsed.promptTemplates?.length??0)>0],["--no-prompt-templates",parsed.noPromptTemplates===!0],["--theme",(parsed.themes?.length??0)>0],["--use-theme",parsed.useTheme!==void 0],["--no-themes",parsed.noThemes===!0],["--no-context-files",parsed.noContextFiles===!0],["--no-skills",parsed.noSkills===!0],["--no-plugins",parsed.noPlugins===!0],["--no-trace",parsed.noTrace===!0],["--plugin-profile",parsed.pluginProfile!==void 0],["--plugin",(parsed.plugins?.length??0)>0],["--disable-plugin",(parsed.disabledPlugins?.length??0)>0],["--system-prompt",parsed.systemPrompt!==void 0],["--append-system-prompt",(parsed.appendSystemPrompt?.length??0)>0]].flatMap(([flag,passed])=>passed?[flag]:[]);ignoredFlags.length>0&&console.warn(source_default.yellow(`--serve ignores session/model/tool options: ${ignoredFlags.join(", ")}`)),await runServeMode(parsed.serve,{...parsed.serveWorkspaceRoots===void 0?{}:{workspaceRoots:parsed.serveWorkspaceRoots},...parsed.sessionDir===void 0?{}:{sessionDir:parsed.sessionDir},...processHostLogger===void 0?{}:{hostLogger:processHostLogger}});return}await handleSuiteLifecycleCommands(parsed,cwd,agentDir),sweepSuiteTrash(agentDir).catch(()=>{});let appMode=resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);parsed.subagentRunner!==!0&&appMode!=="interactive"&&!isPlainRuntimeMetadataCommand(parsed)&&takeOverStdout(),parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir),startupSettingsDiagnostics=collectSettingsDiagnostics(startupSettingsManager);appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme});let envSessionDir=process.env[ENV_SESSION_DIR],sessionDir=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir?expandTildePath(envSessionDir):void 0)??startupSettingsManager.getSessionDir(),sessionManager=await createSessionManager(parsed,cwd,sessionDir,startupSettingsManager),missingSessionCwdIssue=getMissingSessionCwdIssue(sessionManager,cwd);if(missingSessionCwdIssue)if(appMode==="interactive"){let selectedCwd=await promptForMissingSessionCwd(missingSessionCwdIssue,startupSettingsManager);selectedCwd||process.exit(0),sessionManager=SessionManager.open(missingSessionCwdIssue.sessionFile,sessionDir,selectedCwd)}else console.error(source_default.red(new MissingSessionCwdError(missingSessionCwdIssue).message)),process.exit(1);if(parsed.name!==void 0){let name=normalizeSessionName(parsed.name);name===void 0&&(console.error(source_default.red("Error: --name requires a non-empty value")),process.exit(1)),sessionManager.appendSessionInfo(name)}time("createSessionManager");let cliPluginSelection=await resolveCliPluginSelection(parsed,agentDir,sessionManager.getCwd()),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createInteractionHostSlot=()=>{let target;return{host:{notify:request=>target?.notify(request),prompt:(request,context)=>target?target.prompt(request,context):Promise.resolve({status:"unavailable"})},setTarget:next=>{target=next}}},interactionHostSlots={interactive:createInteractionHostSlot(),rpc:createInteractionHostSlot()},startupPluginBootstrap,runStartupPluginBootstrap=bootstrapCwd=>(startupPluginBootstrap??=runNodePluginBootstrapV1({agentDir,cwd:bootstrapCwd}).catch(error2=>({version:1,status:"failed",actions:[],diagnostics:[{code:"bootstrap_failed",message:`Startup plugin bootstrap failed: ${error2 instanceof Error?error2.message:String(error2)}`}],durationMs:0})),startupPluginBootstrap),createRuntime=async({cwd:cwd2,agentDir:agentDir2,sessionManager:sessionManager2,childProfile,childModelId,subagentCommunicationWiring})=>{let runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2);if(!parsed.noPlugins){let bootstrapResult=await runStartupPluginBootstrap(cwd2);for(let diagnostic5 of bootstrapResult.diagnostics)console.error(source_default.yellow(`Plugin bootstrap ${diagnostic5.code}: ${diagnostic5.message}`))}let resolveActivePluginBindings=options?.resolveActivePluginBindings??createDefaultActivePluginBindingsResolverV1(),activeBindings,pluginBindingDiagnostics=[];if(!parsed.noPlugins&&options?.manifestOverrides===void 0)try{let resolvedBindings=await resolveActivePluginBindings({cwd:cwd2,agentDir:agentDir2});activeBindings=resolvedBindings,pluginBindingDiagnostics=resolvedBindings.diagnostics.map(item=>({type:resolvedBindings.status==="unavailable"?"warning":"info",message:`Active plugin binding ${item.code}: ${item.message}`}))}catch{pluginBindingDiagnostics=[{type:"error",message:"Active plugin binding resolver failed; no installed version was selected"}]}let activeManifestOverrides=activeBindings?.status==="ready"?activeBindings.manifestOverrides:void 0,activeVerifiedPlugins=activeBindings?.status==="ready"?activeBindings.verifiedPlugins:void 0,activeInstalledCapabilityPlugins=activeBindings?.status==="ready"?[...activeBindings.installedManifestPaths].map(([pluginId,manifestPath])=>({pluginId,manifestPath})):void 0,pluginHost=options?.pluginHost??(parsed.noPlugins||cliPluginSelection.profileId===void 0&&activeBindings===void 0?void 0:defaultPluginHostFactsV1()),verifiedPlugins=options?.verifiedPlugins??(cliPluginSelection.profileId===void 0?activeVerifiedPlugins:[...defaultBuiltinVerifiedPluginsV1(cliPluginSelection.profileId).filter(builtin=>!activeVerifiedPlugins?.some(active=>active.pluginId===builtin.pluginId&&active.version===builtin.version)),...activeVerifiedPlugins??[]]),services2=await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),suite:parsed.suite,suiteAssembly:!0,...parsed.noPlugins||cliPluginSelection.profileId===void 0?{}:{pluginProfileId:cliPluginSelection.profileId},...parsed.noPlugins||cliPluginSelection.selectedPluginIds===void 0?{}:{selectedPluginIds:cliPluginSelection.selectedPluginIds},...parsed.noPlugins||cliPluginSelection.disabledPluginIds===void 0?{}:{disabledPluginIds:cliPluginSelection.disabledPluginIds},...parsed.noPlugins||pluginHost===void 0?{}:{pluginHost},...parsed.noPlugins||verifiedPlugins===void 0?{}:{verifiedPlugins},...parsed.noPlugins||options?.manifestOverrides===void 0?activeManifestOverrides===void 0?{}:{manifestOverrides:activeManifestOverrides}:{manifestOverrides:options.manifestOverrides},...parsed.noPlugins||activeInstalledCapabilityPlugins===void 0?{}:{installedCapabilityPlugins:activeInstalledCapabilityPlugins},...pluginBindingDiagnostics.length===0?{}:{pluginBindingDiagnostics},resourceLoaderOptions:{additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:[...parsed.appendSystemPrompt??[],...childProfile?.systemPromptAppend===void 0?[]:[childProfile.systemPromptAppend]]}}),{settingsManager:settingsManager2,modelRuntime:modelRuntime2}=services2,diagnostics=[...cliPluginSelection.diagnostics,...services2.diagnostics,...collectSettingsDiagnostics(settingsManager2)],modelPatterns=parsed.models??settingsManager2.getEnabledModels(),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime2,{signal:AbortSignal.timeout(15e3)}):[],profileModel=childModelId===void 0?void 0:(()=>{let entry=scopedModels.find(candidate=>candidate.model.id===childModelId);if(entry===void 0){let available=scopedModels.map(candidate=>candidate.model.id).sort();throw new Error(`agent task child profile model ${JSON.stringify(childModelId)} is not among the runner's scoped models`+(available.length===0?" (none configured)":`; available: ${available.join(", ")}`))}return entry.model})(),sessionContext=sessionManager2.buildSessionContext(),{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(parsed,scopedModels,sessionContext.messages.length>0,modelRuntime2,settingsManager2);diagnostics.push(...sessionOptionDiagnostics);let resumedSessionModel=(()=>{if(sessionOptions.model)return;let persisted=sessionContext.model;if(persisted)return modelRuntime2.getModel(persisted.provider,persisted.modelId)??void 0})();parsed.apiKey&&(sessionOptions.model?await modelRuntime2.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));let childProfileMode=childProfile!==void 0&&childProfile.mode==="readonly"&&parsed.subagentRunner===!0?"readonly":void 0,created=await createAgentSessionFromServices({services:services2,sessionManager:sessionManager2,model:profileModel??sessionOptions.model??resumedSessionModel,thinkingLevel:childProfile?.thinkingLevel??sessionOptions.thinkingLevel,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools,suite:sessionOptions.suite,discoverCapabilityPlugins:parsed.noPlugins?!1:void 0,traceEnabled:parsed.noTrace===!0?!1:void 0,...typeof process.env.OTEL_EXPORTER_OTLP_ENDPOINT=="string"&&process.env.OTEL_EXPORTER_OTLP_ENDPOINT.trim().length>0?{traceOptions:{otlp:{endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT.trim()}}}:{},hostLogger:processHostLogger,...childProfileMode===void 0?{}:{capabilityMode:childProfileMode},...subagentCommunicationWiring===void 0?{}:{subagentCommunicationWiring},subagentPoolFromSelfInvocation:!0,...appMode==="interactive"?{interactionHost:interactionHostSlots.interactive.host}:{},...appMode==="rpc"?{interactionHost:interactionHostSlots.rpc.host}:{}});for(let rejection of created.pluginRejections)diagnostics.push({type:"warning",message:`Capability plugin rejected (${rejection.code}): ${rejection.pluginId??rejection.manifestPath}: ${rejection.message}`});let cliThinkingOverride=parsed.thinking!==void 0||cliThinkingFromModel;if(created.session.model&&cliThinkingOverride&&created.session.setThinkingLevel(created.session.thinkingLevel),childProfile?.tools!==void 0){let narrowed=created.session.getActiveToolNames().filter(name=>childProfile.tools?.includes(name));created.session.setActiveToolsByName(narrowed)}return{...created,services:{...services2,observabilityGetMetricsRef:created.session.observabilityGetMetricsRef},diagnostics,...childProfile===void 0?{}:{childFacts:(()=>{let sessionApi=created.session.getSessionAPI(),systemPromptOptions=sessionApi.getSystemPromptOptions?.();return{activeTools:created.session.getActiveToolNames(),...childProfile?.thinkingLevel===void 0?{}:{thinkingLevel:sessionApi.getThinkingLevel?.()},...systemPromptOptions?.appendSystemPrompt===void 0?{}:{systemPromptAppend:systemPromptOptions.appendSystemPrompt},...created.session.model===void 0?{}:{model:{provider:created.session.model.provider,id:created.session.model.id,contextWindow:created.session.model.contextWindow,maxTokens:created.session.model.maxTokens,reasoning:created.session.model.reasoning}},capabilityMode:created.session.getCapabilityRuntime().host.mode}})()}}};time("createRuntime");function parseSubagentTaskChildProfile(raw){if(raw===void 0)return;let parsed2=parseAgentTaskChildProfileV1(raw);if(!parsed2.ok)throw new Error(`child task profile is invalid: ${parsed2.message}`);return parsed2.profile}if(parsed.subagentRunner===!0){let runnerSessionCwd=sessionManager.getCwd();await runSubagentTaskRunner({input:process.stdin,output:process.stdout,createSession:createSubagentTaskSessionFactoryV1({createSession:async request=>{let childProfile=parseSubagentTaskChildProfile(request.profile),resumeRead=typeof request.resumeSessionId=="string"&&request.resumeSessionId!==""?readAgentSession({agentDir,sessionId:request.resumeSessionId}):void 0;if(typeof request.resumeSessionId=="string"&&request.resumeSessionId!==""&&(resumeRead===void 0||request.parentSessionId===void 0||resumeRead.parentAgentSession!==request.parentSessionId))throw new Error(`resume target ${request.resumeSessionId} is not a persisted child of session ${String(request.parentSessionId)}`);let resumeFilePath=resumeRead!==void 0&&typeof request.resumeSessionId=="string"?findSessionFile2(agentSessionsDir2(agentDir),request.resumeSessionId):void 0,leafIdentity={current:void 0},requireIdentity=()=>{if(leafIdentity.current===void 0)throw new Error("leaf session identity is not bound yet");return leafIdentity.current},leafWiring=request.parentSessionId===void 0?{}:{postEscalate:text=>{createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).postEscalate(requireIdentity(),text)},sendSibling:(toSessionId,text)=>{createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).postSibling(requireIdentity(),toSessionId,text)},drainInbox:limit=>createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).drainInbox(requireIdentity(),limit)},created=await createRuntime({cwd:runnerSessionCwd,agentDir,sessionManager:resumeFilePath!==void 0&&request.resumeSessionId!==void 0?SessionManager.open(resumeFilePath,agentSessionsDir2(agentDir),runnerSessionCwd):SessionManager.create(runnerSessionCwd,agentSessionsDir2(agentDir),{...request.parentSessionId===void 0?{}:{parentAgentSession:request.parentSessionId},...request.parentTraceId===void 0?{}:{parentTraceId:request.parentTraceId},...childProfile?.roleId===void 0?{}:{agentRole:childProfile.roleId}}),...childProfile===void 0?{}:{childProfile},...childProfile?.model===void 0?{}:{childModelId:childProfile.model},...Object.keys(leafWiring).length===0?{}:{subagentCommunicationWiring:leafWiring}}),session2=created.session,sessionApi=session2.getSessionAPI();return leafIdentity.current=sessionApi.getAgentSessionId?.()??sessionApi.getSessionId(),{prompt:text=>session2.prompt(text,{expandPromptTemplates:!1}),abort:reason=>session2.abort(reason),dispose:()=>session2.dispose(),getMessages:()=>sessionApi.getMessages(),getSessionId:()=>sessionApi.getSessionId(),onProgress:createTurnProgressSourceV1(session2),...sessionApi.steer===void 0?{}:{steer:text=>{let steerFn=sessionApi.steer;return steerFn===void 0?Promise.resolve():steerFn.call(sessionApi,text)}},...created.childFacts===void 0?{}:{facts:()=>created.childFacts}}}})}).done;return}let runtime,pendingSuiteSelector;try{runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager})}catch(error2){if(error2 instanceof SuiteRebindError&&(console.error(source_default.red(`Error: ${error2.message}`)),process.exit(1)),!(error2 instanceof SuiteResolutionError))throw error2;appMode!=="interactive"&&(console.error(source_default.red(`Error: ${error2.message}`)),process.exit(1)),pendingSuiteSelector={requestedId:error2.requestedId,available:error2.availableSuiteIds},parsed.suite=void 0,process.env[SUITE_ENV_VAR]===error2.requestedId&&delete process.env[SUITE_ENV_VAR];try{runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager})}catch(retryError){throw retryError instanceof SuiteResolutionError&&(console.error(source_default.red(`Error: ${retryError.message}`)),process.exit(1)),retryError}}time("createAgentSessionRuntime");let{services,session,modelFallbackMessage}=runtime,{settingsManager,modelRuntime}=services;if(setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs()),parsed.help&&(reportDiagnostics(startupSettingsDiagnostics),printHelp(),process.exit(0)),parsed.listModels!==void 0){reportDiagnostics(startupSettingsDiagnostics);let searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let stdinContent;appMode!=="rpc"&&(stdinContent=await readPipedStdin(),stdinContent!==void 0&&appMode==="interactive"&&(appMode="print")),time("readPipedStdin");let{initialMessage,initialImages}=await prepareInitialMessage(parsed,settingsManager.getImageAutoResize(),stdinContent);time("prepareInitialMessage"),initTheme(settingsManager.getTheme(),appMode==="interactive"),time("initTheme"),appMode==="interactive"&&deprecationWarnings.length>0&&await showDeprecationWarnings(deprecationWarnings),time("resolveModelScope");let allStartupDiagnostics=deduplicateDiagnostics([...startupSettingsDiagnostics,...runtime.diagnostics]),startupDiagnostics=filterAcknowledgedSuiteNotices(allStartupDiagnostics,settingsManager);await settingsManager.flush().catch(()=>{});let hasRuntimeErrors=runtime.diagnostics.some(diagnostic5=>diagnostic5.type==="error");if((appMode!=="interactive"||hasRuntimeErrors)&&reportDiagnostics(startupDiagnostics),hasRuntimeErrors&&process.exit(1),appMode==="interactive")for(let rejection of runtime.pluginRejections)console.error(source_default.yellow(`Warning: capability plugin rejected (${rejection.code}): ${rejection.pluginId??rejection.manifestPath}: ${rejection.message}`));time("createAgentSession");let noModelResolved=!session.model||session.model.provider==="unknown"&&session.model.id==="unknown";appMode!=="interactive"&&noModelResolved&&(console.error(source_default.red(modelFallbackMessage??formatNoModelsAvailableMessage())),process.exit(1));let startupBenchmark=isTruthyEnvFlag(process.env.AGENT_FORGE_STARTUP_BENCHMARK);if(startupBenchmark&&appMode!=="interactive"&&(console.error(source_default.red("Error: AGENT_FORGE_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!offlineMode&&appMode==="rpc"){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);modelRuntime.refresh({signal:controller.signal}).catch(()=>{}).finally(()=>clearTimeout(timeout))}if(appMode==="rpc")printTimings(),await runRpcMode(runtime,{interactionHostSlot:interactionHostSlots.rpc,getMetrics:options2=>runtime.observabilityGetMetricsRef?.current?.(options2)});else if(appMode==="interactive"){let interactiveMode=new InteractiveMode(runtime,{getMetrics:options2=>runtime.observabilityGetMetricsRef?.current?.(options2),migratedProviders,startupDiagnostics,modelFallbackMessage,initialMessage,initialImages,initialMessages:parsed.messages,verbose:parsed.verbose,tuiMode:parsed.tuiMode,initialThemeSetting:parsed.useTheme,pendingSuiteSelector,settingsManager});if(interactionHostSlots.interactive.setTarget(interactiveMode.createInteractionHostV1()),startupBenchmark){await interactiveMode.init(),time("interactiveMode.init"),await new Promise(resolve25=>setTimeout(resolve25,150)),interactiveMode.stop(),stopThemeWatcher(),printTimings(),process.stdout.writableLength>0&&await new Promise(resolve25=>process.stdout.once("drain",resolve25)),process.stderr.writableLength>0&&await new Promise(resolve25=>process.stderr.once("drain",resolve25));return}printTimings(),await interactiveMode.run()}else{printTimings();let exitCode=await runPrintMode(runtime,{mode:toPrintOutputMode(appMode),messages:parsed.messages,initialMessage,initialImages});stopThemeWatcher(),restoreStdout(),exitCode!==0&&(process.exitCode=exitCode);return}}export{getPackageDir,getReadmePath,getDocsPath,getExamplesPath,APP_NAME,CONFIG_DIR_NAME,VERSION,getAgentDir,getSessionsDir,configureHttpDispatcher,Text,Loader,CancellableLoader,Container,SelectList,Spacer,EXPERIMENTAL_PUBLIC_API_VERSION,LifecycleTransformError,LifecycleExecuteError,SUMMARY_MODEL_INVOCATION_ERROR_CODES,createDisposableRegistration,createEventEnvelope,detachedSessionSnapshot,parseCapabilityPluginManifest,MEMORY_RECALL_TOOL_NAME,dist_exports,parseArgs,resolveModelScopeWithDiagnostics,resolveCliModel,getShellConfig,getPowerShellConfig,sanitizeBinaryOutput,killProcessTree,readStoredCredential,CredentialSynchronizationError,ModelRuntime,convertToPng,resizeImage,formatDimensionNote,detectSupportedImageMimeTypeFromFile,stableJsonDigest,buildProfileIdentityV1,profileIdentitiesCompatible,PLUGIN_DISPOSE_EVENT_ID,PLUGIN_DISPOSE_EVENT_VERSION,PLUGIN_READY_EVENT_ID,PLUGIN_READY_EVENT_VERSION,SESSION_CONTEXT_REPLACED_EVENT_ID,SESSION_CONTEXT_REPLACED_EVENT_VERSION,SESSION_RELOAD_EVENT_ID,SESSION_RELOAD_EVENT_VERSION,MODEL_RESPONSE_EVENT_ID,MODEL_RESPONSE_EVENT_VERSION,MODEL_STREAM_EVENT_ID,MODEL_STREAM_EVENT_VERSION,TOOL_RESULT_EVENT_ID,TOOL_RESULT_EVENT_VERSION,TOOL_CALL_EVENT_ID,TOOL_CALL_EVENT_VERSION,TOOL_RESULT_RAW_EVENT_ID,TOOL_RESULT_RAW_EVENT_VERSION,TOOL_EXECUTE_EVENT_ID,TOOL_EXECUTE_EVENT_VERSION,TOOL_COMMIT_EVENT_ID,TOOL_COMMIT_EVENT_VERSION,OPERATION_END_EVENT_ID,OPERATION_END_EVENT_VERSION,validatePluginDisposeEventDataV1,validatePluginReadyEventDataV1,validateSessionContextReplacedEventDataV1,validateSessionReloadEventDataV1,validateModelResponseEventDataV1,validateModelStreamEventDataV1,validateToolResultEventDataV1,validateToolCallEventDataV1,validateToolExecuteEventDataV1,validateToolCommitEventDataV1,validateToolResultRawEventDataV1,TOOL_RESULT_TRANSFORM_EVENT_ID,TOOL_RESULT_TRANSFORM_EVENT_VERSION,validateToolResultTransformEventDataV1,validateOperationEndEventDataV1,CAPABILITY_CALL_EVENT_ID,CAPABILITY_CALL_EVENT_VERSION,validateCapabilityCallEventDataV1,OPERATION_START_EVENT_ID,OPERATION_START_EVENT_VERSION,OPERATION_STEP_EVENT_ID,OPERATION_STEP_EVENT_VERSION,validateOperationStartEventDataV1,validateOperationStepEventDataV1,OPERATION_CANCEL_EVENT_ID,OPERATION_CANCEL_EVENT_VERSION,validateOperationCancelEventDataV1,discoverCapabilityPluginManifests,loadCapabilityPlugin,loadCapabilityPluginSync,loadCapabilityPluginFromManifest,ecosystem_exports,assembleProfile,replaceProfilePlugin,listBuiltinPluginProfilesV1,listBuiltinPluginManifestsV1,resolveBuiltinPluginProfileV1,plugin_manager_controller_exports,DurableServiceErrorV1,durableLogPath,createFileDurableStoreBackend,createDurableService,projectSessionTranscript,CodingAgentSessionRuntime,CodingAgentServerService,assembleCodingAgentServer,DEFAULT_SUITE_ID,isBuiltinSuiteId,buildResolvedAgentProfileV1,parseFrontmatter,stripFrontmatter,createSyntheticSourceInfo,loadSkillsFromDir,formatSkillsForPrompt,loadSkills,createProfileLock,verifyProfileLock,replaceProfileLock,createProfileRegistry,SuiteResolutionError,listSuiteIds,BOOTSTRAP_LIFECYCLE_PLUGIN_ID,SESSION_COMPACTION_COMMIT_EVENT_ID,SESSION_COMPACTION_COMMIT_EVENT_VERSION,validateSessionCompactionCommitEventDataV1,installBootstrapLifecycle,defineTool,AgentCompositionRuntime,createAgentCompositionRuntime,convertToLlm2 as convertToLlm,SessionHeaderScanLimitError,FileSessionStorageProvider,CURRENT_SESSION_VERSION,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext2 as buildSessionContext,SessionManager,serializeConversation2 as serializeConversation,DEFAULT_COMPACTION_SETTINGS2 as DEFAULT_COMPACTION_SETTINGS,calculateContextTokens2 as calculateContextTokens,getLastAssistantUsage2 as getLastAssistantUsage,shouldCompact2 as shouldCompact,estimateTokens2 as estimateTokens,findTurnStartIndex2 as findTurnStartIndex,findCutPoint2 as findCutPoint,generateSummary2 as generateSummary,generateSummaryWithUsage2 as generateSummaryWithUsage,compact2 as compact,collectEntriesForBranchSummary2 as collectEntriesForBranchSummary,prepareBranchEntries2 as prepareBranchEntries,generateBranchSummary2 as generateBranchSummary,BOOTSTRAP_COMPACTION_PLUGIN_ID,DEFAULT_COMPACTION_POLICY_NAME,installBootstrapCompactionPolicy,BOOTSTRAP_RETRY_PLUGIN_ID,DEFAULT_RETRY_POLICY_NAME,installBootstrapRetryPolicy,Theme,getAvailableThemes,initTheme,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,keyText,keyHint,rawKeyHint,truncateToVisualLines,DEFAULT_MAX_LINES2 as DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES3 as DEFAULT_MAX_BYTES,formatSize2 as formatSize,truncateHead2 as truncateHead,truncateTail2 as truncateTail,truncateLine,createLocalBashOperations,createBashToolDefinition,createBashTool2 as createBashTool,renderDiff,generateUnifiedPatch2 as generateUnifiedPatch,generateDiffString2 as generateDiffString,withFileMutationQueue2 as withFileMutationQueue,createEditToolDefinition,createEditTool2 as createEditTool,createFindToolDefinition,createFindTool,createGrepToolDefinition,createGrepTool,createLsToolDefinition,createLsTool,createLocalPowerShellOperations,createPowerShellToolDefinition,createPowerShellTool,createReadToolDefinition,createReadTool2 as createReadTool,createWriteToolDefinition,createWriteTool2 as createWriteTool,createCodingTools,createReadOnlyTools,BOOTSTRAP_TOOLS_PLUGIN_ID,installBootstrapTools,installSessionBootstrapTools,resolvePluginCapabilityOrder,validateExecutionFactsV1,validateRetryScheduleV1,createCapabilityRuntime,parseSkillBlock,AgentSession,DefaultPackageManager,SettingsManager,loadProjectContextFiles,DefaultResourceLoader,createAgentSessionServices,createAgentSessionFromServices,AgentSessionRuntime,createAgentSessionRuntime,createAgentSession,createStableAgentSession,createStableAgentSessionRuntime,createFileSessionSource,startCodingAgentRemoteServer,DynamicBorder,SessionSelectorComponent,DialogInputComponent,DialogSelectorComponent,createProfileMigrationPolicy,SUITE_DELETE_CONFIRM_TOKEN,SuiteLifecycleError,createSuite,findSuiteSessionRefs,deleteSuite,resetSuite,clearDanglingSuiteSettings,copyToClipboard,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CustomEditor,CustomMessageComponent,FooterComponent,SettingsSelectorComponent,SkillInvocationMessageComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,LoginDialogComponent,OAuthSelectorComponent,DialogEditorComponent,ModelSelectorComponent,ThinkingSelectorComponent,UserMessageSelectorComponent,InteractiveMode,createStdioChannelAdapter,createHostOutputProjector,runPrintMode,RpcClient,runRpcMode,PluginManagerEntryComponent,plugin_selection_controller_exports,main};
1579
+ `),console.log(plan.diffText),process.stdin.isTTY||(console.error(source_default.red(`Refusing to reset suite "${id}" without an interactive confirmation (non-interactive stdin). Review the diff above and re-run in a terminal to confirm.`)),process.exit(1)),await promptConfirm(`Apply reset of suite "${id}"?`)||(console.log(`Aborted: suite "${id}" was not reset.`),process.exit(1));let result=plan.apply();console.log(`Suite "${id}" was reset to the factory contents (profile lock generation ${result.lock.generation}).`)}catch(error2){printSuiteLifecycleError(error2),process.exit(1)}process.exit(0)}}function validateForkFlags(parsed){if(!parsed.fork)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.noSession?"--no-session":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1))}function validateSessionIdFlags(parsed){if(parsed.sessionId===void 0)return;let conflictingFlags=[parsed.session?"--session":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}. To resume that exact session, drop the other flags and use --session-id alone (or use --continue to resume the most recent session).`)),process.exit(1));try{assertValidSessionId(parsed.sessionId)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function openSessionOrExit(path15,sessionDir){try{return SessionManager.open(path15,sessionDir)}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}function forkSessionOrExit(sourcePath,cwd,sessionDir,sessionId){try{return SessionManager.forkFrom(sourcePath,cwd,sessionDir,{id:sessionId})}catch(error2){let message=error2 instanceof Error?error2.message:String(error2);console.error(source_default.red(`Error: ${message}`)),process.exit(1)}}async function createSessionManager(parsed,cwd,sessionDir,settingsManager){if(parsed.noSession||parsed.help||parsed.listModels!==void 0)return SessionManager.inMemory(cwd,parsed.sessionId!==void 0?{id:parsed.sessionId}:void 0);if(parsed.fork){parsed.sessionId&&await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir)&&(console.error(source_default.red(`Session already exists with id '${parsed.sessionId}'`)),process.exit(1));let resolved=await resolveSessionPath(parsed.fork,cwd,sessionDir);switch(resolved.type){case"path":case"local":case"global":return forkSessionOrExit(resolved.path,cwd,sessionDir,parsed.sessionId);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.session){let resolved=await resolveSessionPath(parsed.session,cwd,sessionDir);switch(resolved.type){case"path":case"local":return openSessionOrExit(resolved.path,sessionDir);case"global":return console.log(source_default.yellow(`Session found in different project: ${resolved.cwd}`)),await promptConfirm("Fork this session into current directory?")||(console.log(source_default.dim("Aborted.")),process.exit(0)),forkSessionOrExit(resolved.path,cwd,sessionDir);case"not_found":console.error(source_default.red(`No session found matching '${resolved.arg}'`)),process.exit(1)}}if(parsed.resume)try{let selectedPath=await selectSession(onProgress=>SessionManager.list(cwd,sessionDir,onProgress),onProgress=>SessionManager.listAll(sessionDir,onProgress),settingsManager);return selectedPath||(console.log(source_default.dim("No session selected")),process.exit(0)),SessionManager.open(selectedPath,sessionDir)}finally{stopThemeWatcher()}if(parsed.continue)return SessionManager.continueRecent(cwd,sessionDir);if(parsed.sessionId){let existingSession=await findLocalSessionByExactId(parsed.sessionId,cwd,sessionDir);if(existingSession)return SessionManager.open(existingSession.path,sessionDir);console.error(source_default.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`))}return SessionManager.create(cwd,sessionDir,{id:parsed.sessionId})}function buildSessionOptions(parsed,scopedModels,hasExistingSession,modelRuntime,settingsManager){let options={};parsed.rebindSuite&&(options.allowSuiteRebind=!0);let diagnostics=[],cliThinkingFromModel=!1;if(parsed.model){let resolved=resolveCliModel({cliProvider:parsed.provider,cliModel:parsed.model,cliThinking:parsed.thinking,modelRuntime});resolved.warning&&diagnostics.push({type:"warning",message:resolved.warning}),resolved.error&&diagnostics.push({type:"error",message:resolved.error}),resolved.model&&(options.model=resolved.model,!parsed.thinking&&resolved.thinkingLevel&&(options.thinkingLevel=resolved.thinkingLevel,cliThinkingFromModel=!0))}if(!options.model&&scopedModels.length>0&&!hasExistingSession){let savedProvider=settingsManager.getDefaultProvider(),savedModelId=settingsManager.getDefaultModel(),savedModel=savedProvider&&savedModelId?modelRuntime.getModel(savedProvider,savedModelId):void 0,savedInScope=savedModel?scopedModels.find(sm=>modelsAreEqual(sm.model,savedModel)):void 0;savedInScope?(options.model=savedInScope.model,!parsed.thinking&&savedInScope.thinkingLevel&&(options.thinkingLevel=savedInScope.thinkingLevel)):(options.model=scopedModels[0].model,!parsed.thinking&&scopedModels[0].thinkingLevel&&(options.thinkingLevel=scopedModels[0].thinkingLevel))}return parsed.thinking&&(options.thinkingLevel=parsed.thinking),scopedModels.length>0&&(options.scopedModels=scopedModels.map(sm=>({model:sm.model,thinkingLevel:sm.thinkingLevel}))),parsed.noTools?options.noTools="all":parsed.noBuiltinTools&&(options.noTools="builtin"),parsed.tools&&(options.tools=[...parsed.tools]),parsed.excludeTools&&(options.excludeTools=[...parsed.excludeTools]),parsed.suite&&(options.suite=parsed.suite),{options,cliThinkingFromModel,diagnostics}}function resolveCliPaths(cwd,paths){return paths?.map(value=>isLocalPath(value)?resolvePath(value,cwd):value)}async function promptForMissingSessionCwd(issue,settingsManager){return showStartupSelector(settingsManager,formatMissingSessionCwdPrompt(issue),[{label:"Continue",value:issue.fallbackCwd},{label:"Cancel",value:void 0}])}function isBuiltinPluginProfileId(value){return listBuiltinPluginProfilesV1().some(profile=>profile.id===value)}function selectionDiagnostics(status2,diagnostics){return diagnostics.map(item=>({type:"error",message:`Plugin selection ${status2} (${item.code}): ${item.message}`}))}async function resolveCliPluginSelection(parsed,agentDir,cwd){if(!(parsed.pluginProfile!==void 0||parsed.plugins!==void 0||parsed.disabledPlugins!==void 0||parsed.pluginSelectionScope!==void 0)||parsed.noPlugins)return{diagnostics:[]};if(parsed.pluginProfile===void 0&&parsed.plugins===void 0&&parsed.disabledPlugins===void 0)return{diagnostics:[{type:"error",message:"--plugin-scope requires an explicit plugin selection"}]};let diagnostics=[],selectionPath=(parsed.pluginSelectionScope??"global")==="project"?join68(cwd,CONFIG_DIR_NAME,".plugin-selection.json"):join68(agentDir,".plugin-selection.json"),store=createPluginSelectionStoreV1({filePath:selectionPath}),persistedResult;try{persistedResult=await store.read()}catch{return diagnostics.push({type:"error",message:"Plugin selection could not be read"}),{diagnostics}}if(persistedResult.status==="invalid"||persistedResult.status==="cancelled")return diagnostics.push(...selectionDiagnostics(persistedResult.status,persistedResult.diagnostics)),{diagnostics};let explicitProfileId=parsed.pluginProfile,profileId;if(explicitProfileId!==void 0){if(!isBuiltinPluginProfileId(explicitProfileId))return diagnostics.push({type:"error",message:`Unknown plugin profile: ${explicitProfileId}`}),{diagnostics};profileId=explicitProfileId}let persistedSelection2;if(profileId!==void 0)persistedSelection2=persistedResult.snapshot.selections.find(selection=>selection.profileId===profileId);else if(parsed.plugins!==void 0||parsed.disabledPlugins!==void 0){if(persistedResult.snapshot.selections.length!==1)return diagnostics.push({type:"error",message:persistedResult.snapshot.selections.length===0?"--plugin/--disable-plugin requires --plugin-profile or one persisted plugin profile":"--plugin/--disable-plugin requires --plugin-profile when multiple persisted profiles exist"}),{diagnostics};if(persistedSelection2=persistedResult.snapshot.selections[0],persistedSelection2!==void 0&&isBuiltinPluginProfileId(persistedSelection2.profileId))profileId=persistedSelection2.profileId;else return diagnostics.push({type:"error",message:`Unknown persisted plugin profile: ${persistedSelection2?.profileId??""}`}),{diagnostics}}return{...profileId===void 0?{}:{profileId},...parsed.plugins!==void 0?{selectedPluginIds:Object.freeze([...parsed.plugins])}:persistedSelection2===void 0?{}:{selectedPluginIds:persistedSelection2.selectedPluginIds},...parsed.disabledPlugins!==void 0?{disabledPluginIds:Object.freeze([...parsed.disabledPlugins])}:persistedSelection2===void 0?{}:{disabledPluginIds:persistedSelection2.disabledPluginIds},diagnostics}}async function main(args,options){resetTimings();let offlineMode=args.includes("--offline")||isTruthyEnvFlag(process.env.AGENT_FORGE_OFFLINE);if(offlineMode&&(process.env.AGENT_FORGE_OFFLINE="1",process.env.AGENT_FORGE_SKIP_VERSION_CHECK="1"),await runAuthCommand(args)||await handlePluginEcosystemCommand(args))return;process.platform==="win32"&&cleanupWindowsSelfUpdateQuarantine(getPackageDir()),cleanupManagedInstall();let cwd=process.cwd(),agentDir=getAgentDir(),bootstrapSettingsManager=SettingsManager.create(cwd,agentDir);if(applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(),await handlePackageCommand(args)){let exitCode=process.exitCode??0;if(process.platform==="win32"&&exitCode===0&&args[0]==="update")return;process.exit(exitCode);return}let configCommandOptions=options?.pluginManagerController===void 0&&options?.projectPluginManagerController===void 0?void 0:{...options?.pluginManagerController===void 0?{}:{pluginManagerController:options.pluginManagerController},...options?.projectPluginManagerController===void 0?{}:{projectPluginManagerController:options.projectPluginManagerController}};if(await handleConfigCommand(args,configCommandOptions))return;let parsed=parseArgs(args);if(parsed.diagnostics.length>0){for(let d2 of parsed.diagnostics){let color=d2.type==="error"?source_default.red:source_default.yellow;console.error(color(`${d2.type==="error"?"Error":"Warning"}: ${d2.message}`))}parsed.diagnostics.some(d2=>d2.type==="error")&&process.exit(1)}time("parseArgs");let envLogLevel=process.env.AGENT_FORGE_LOG_LEVEL,hostLogLevel=parsed.logLevel??(envLogLevel!==void 0&&isValidHostLogLevel(envLogLevel)?envLogLevel:void 0),rawLogMaxAgeDays=process.env.AGENT_FORGE_LOG_MAX_AGE_DAYS,hostLogMaxAgeDays=rawLogMaxAgeDays!==void 0&&/^\d+$/.test(rawLogMaxAgeDays)?Number.parseInt(rawLogMaxAgeDays,10):void 0;processHostLogger===void 0&&(processHostLogger=createHostLogger({dir:join68(agentDir,"logs"),...hostLogLevel===void 0?{}:{level:hostLogLevel},...hostLogMaxAgeDays===void 0?{}:{maxAgeDays:hostLogMaxAgeDays}}));let rawTraceMaxAgeDays=process.env.AGENT_FORGE_TRACE_MAX_AGE_DAYS,traceMaxAgeDays=rawTraceMaxAgeDays!==void 0&&/^\d+$/.test(rawTraceMaxAgeDays)?Number.parseInt(rawTraceMaxAgeDays,10):0;if(traceMaxAgeDays>0){let traceSweep=sweepTraceFiles(getSessionsDir(),{maxAgeDays:traceMaxAgeDays,now:Date.now});traceSweep.deleted>0&&processHostLogger.info("retention","trace sweep removed expired trace files",{fields:{deleted:traceSweep.deleted,failed:traceSweep.failed}}),traceSweep.failed>0&&processHostLogger.warn("retention","trace sweep finished with failures",{fields:{deleted:traceSweep.deleted,failed:traceSweep.failed}})}if(parsed.version&&(console.log(VERSION),process.exit(0)),parsed.export){let result;try{let outputPath=parsed.messages.length>0?parsed.messages[0]:void 0;result=await exportFromFile(parsed.export,outputPath)}catch(error2){let message=error2 instanceof Error?error2.message:"Failed to export session";console.error(source_default.red(`Error: ${message}`)),process.exit(1)}console.log(`Exported to: ${result}`),process.exit(0)}if(parsed.trace!==void 0){let envSessionDir2=process.env[ENV_SESSION_DIR],sessionDir2=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir2?expandTildePath(envSessionDir2):void 0)??bootstrapSettingsManager.getSessionDir(),result=await runTraceView(parsed.trace,{json:parsed.traceJson===!0,cwd,...sessionDir2===void 0?{}:{sessionDir:sessionDir2},...parsed.traceKind===void 0?{}:{kinds:parsed.traceKind},...parsed.traceLimit===void 0?{}:{limit:parsed.traceLimit}});result.ok||(console.error(source_default.red(`Error: ${result.message}`)),process.exit(1)),process.exit(0)}if(parsed.serve!==void 0){if(parsed.help||parsed.listModels!==void 0){runMigrations(cwd),reportDiagnostics(collectSettingsDiagnostics(bootstrapSettingsManager)),parsed.help&&(printHelp(),process.exit(0));let modelRuntime2=await ModelRuntime.create({signal:AbortSignal.timeout(15e3)}),searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime2,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let conflictingFlags=[parsed.print?"--print":void 0,parsed.messages.length>0?"positional args":void 0,parsed.fileArgs.length>0?"@file args":void 0,parsed.continue?"--continue":void 0,parsed.resume?"--resume":void 0,parsed.session?"--session":void 0,parsed.sessionId?"--session-id":void 0,parsed.fork?"--fork":void 0,parsed.noSession?"--no-session":void 0,parsed.mode?"--mode":void 0,parsed.suiteCreate?"--suite-create":void 0,parsed.suiteDelete?"--suite-delete":void 0,parsed.suiteReset?"--suite-reset":void 0,parsed.cloneFrom?"--clone-from":void 0].filter(flag=>flag!==void 0);conflictingFlags.length>0&&(console.error(source_default.red(`Error: --serve cannot be combined with ${conflictingFlags.join(", ")}`)),process.exit(1));let ignoredFlags=[["--name",parsed.name!==void 0],["--thinking",parsed.thinking!==void 0],["--provider",parsed.provider!==void 0],["--model",parsed.model!==void 0],["--api-key",parsed.apiKey!==void 0],["--models",(parsed.models?.length??0)>0],["--verbose",parsed.verbose===!0],["--tui-mode",parsed.tuiMode!==void 0],["--suite",parsed.suite!==void 0],["--tools",(parsed.tools?.length??0)>0],["--exclude-tools",(parsed.excludeTools?.length??0)>0],["--no-tools",parsed.noTools===!0],["--no-builtin-tools",parsed.noBuiltinTools===!0],["--skill",(parsed.skills?.length??0)>0],["--prompt-template",(parsed.promptTemplates?.length??0)>0],["--no-prompt-templates",parsed.noPromptTemplates===!0],["--theme",(parsed.themes?.length??0)>0],["--use-theme",parsed.useTheme!==void 0],["--no-themes",parsed.noThemes===!0],["--no-context-files",parsed.noContextFiles===!0],["--no-skills",parsed.noSkills===!0],["--no-plugins",parsed.noPlugins===!0],["--no-trace",parsed.noTrace===!0],["--plugin-profile",parsed.pluginProfile!==void 0],["--plugin",(parsed.plugins?.length??0)>0],["--disable-plugin",(parsed.disabledPlugins?.length??0)>0],["--system-prompt",parsed.systemPrompt!==void 0],["--append-system-prompt",(parsed.appendSystemPrompt?.length??0)>0]].flatMap(([flag,passed])=>passed?[flag]:[]);ignoredFlags.length>0&&console.warn(source_default.yellow(`--serve ignores session/model/tool options: ${ignoredFlags.join(", ")}`)),await runServeMode(parsed.serve,{...parsed.serveWorkspaceRoots===void 0?{}:{workspaceRoots:parsed.serveWorkspaceRoots},...parsed.sessionDir===void 0?{}:{sessionDir:parsed.sessionDir},...processHostLogger===void 0?{}:{hostLogger:processHostLogger}});return}await handleSuiteLifecycleCommands(parsed,cwd,agentDir),sweepSuiteTrash(agentDir).catch(()=>{});let appMode=resolveAppMode(parsed,process.stdin.isTTY,process.stdout.isTTY);parsed.subagentRunner!==!0&&appMode!=="interactive"&&!isPlainRuntimeMetadataCommand(parsed)&&takeOverStdout(),parsed.mode==="rpc"&&parsed.fileArgs.length>0&&(console.error(source_default.red("Error: @file arguments are not supported in RPC mode")),process.exit(1)),validateForkFlags(parsed),validateSessionIdFlags(parsed);let{migratedAuthProviders:migratedProviders,deprecationWarnings}=runMigrations(cwd);time("runMigrations");let startupSettingsManager=SettingsManager.create(cwd,agentDir),startupSettingsDiagnostics=collectSettingsDiagnostics(startupSettingsManager);appMode==="interactive"&&!parsed.help&&parsed.listModels===void 0&&shouldRunFirstTimeSetup()&&(await showFirstTimeSetup(startupSettingsManager),time("firstTimeSetup")),appMode==="interactive"&&parsed.useTheme!==void 0&&startupSettingsManager.applyOverrides({theme:parsed.useTheme});let envSessionDir=process.env[ENV_SESSION_DIR],sessionDir=(parsed.sessionDir?normalizePath(parsed.sessionDir):void 0)??(envSessionDir?expandTildePath(envSessionDir):void 0)??startupSettingsManager.getSessionDir(),sessionManager=await createSessionManager(parsed,cwd,sessionDir,startupSettingsManager),missingSessionCwdIssue=getMissingSessionCwdIssue(sessionManager,cwd);if(missingSessionCwdIssue)if(appMode==="interactive"){let selectedCwd=await promptForMissingSessionCwd(missingSessionCwdIssue,startupSettingsManager);selectedCwd||process.exit(0),sessionManager=SessionManager.open(missingSessionCwdIssue.sessionFile,sessionDir,selectedCwd)}else console.error(source_default.red(new MissingSessionCwdError(missingSessionCwdIssue).message)),process.exit(1);if(parsed.name!==void 0){let name=normalizeSessionName(parsed.name);name===void 0&&(console.error(source_default.red("Error: --name requires a non-empty value")),process.exit(1)),sessionManager.appendSessionInfo(name)}time("createSessionManager");let cliPluginSelection=await resolveCliPluginSelection(parsed,agentDir,sessionManager.getCwd()),resolvedSkillPaths=resolveCliPaths(cwd,parsed.skills),resolvedPromptTemplatePaths=resolveCliPaths(cwd,parsed.promptTemplates),resolvedThemePaths=resolveCliPaths(cwd,parsed.themes),createInteractionHostSlot=()=>{let target;return{host:{notify:request=>target?.notify(request),prompt:(request,context)=>target?target.prompt(request,context):Promise.resolve({status:"unavailable"})},setTarget:next=>{target=next}}},interactionHostSlots={interactive:createInteractionHostSlot(),rpc:createInteractionHostSlot()},startupPluginBootstrap,runStartupPluginBootstrap=bootstrapCwd=>(startupPluginBootstrap??=runNodePluginBootstrapV1({agentDir,cwd:bootstrapCwd}).catch(error2=>({version:1,status:"failed",actions:[],diagnostics:[{code:"bootstrap_failed",message:`Startup plugin bootstrap failed: ${error2 instanceof Error?error2.message:String(error2)}`}],durationMs:0})),startupPluginBootstrap),createRuntime=async({cwd:cwd2,agentDir:agentDir2,sessionManager:sessionManager2,childProfile,childModelId,subagentCommunicationWiring})=>{let runtimeSettingsManager=SettingsManager.create(cwd2,agentDir2);if(!parsed.noPlugins){let bootstrapResult=await runStartupPluginBootstrap(cwd2);for(let diagnostic5 of bootstrapResult.diagnostics)console.error(source_default.yellow(`Plugin bootstrap ${diagnostic5.code}: ${diagnostic5.message}`))}let resolveActivePluginBindings=options?.resolveActivePluginBindings??createDefaultActivePluginBindingsResolverV1(),activeBindings,pluginBindingDiagnostics=[];if(!parsed.noPlugins&&options?.manifestOverrides===void 0)try{let resolvedBindings=await resolveActivePluginBindings({cwd:cwd2,agentDir:agentDir2});activeBindings=resolvedBindings,pluginBindingDiagnostics=resolvedBindings.diagnostics.map(item=>({type:resolvedBindings.status==="unavailable"?"warning":"info",message:`Active plugin binding ${item.code}: ${item.message}`}))}catch{pluginBindingDiagnostics=[{type:"error",message:"Active plugin binding resolver failed; no installed version was selected"}]}let activeManifestOverrides=activeBindings?.status==="ready"?activeBindings.manifestOverrides:void 0,activeVerifiedPlugins=activeBindings?.status==="ready"?activeBindings.verifiedPlugins:void 0,activeInstalledCapabilityPlugins=activeBindings?.status==="ready"?[...activeBindings.installedManifestPaths].map(([pluginId,manifestPath])=>({pluginId,manifestPath})):void 0,pluginHost=options?.pluginHost??(parsed.noPlugins||cliPluginSelection.profileId===void 0&&activeBindings===void 0?void 0:defaultPluginHostFactsV1()),verifiedPlugins=options?.verifiedPlugins??(cliPluginSelection.profileId===void 0?activeVerifiedPlugins:[...defaultBuiltinVerifiedPluginsV1(cliPluginSelection.profileId).filter(builtin=>!activeVerifiedPlugins?.some(active=>active.pluginId===builtin.pluginId&&active.version===builtin.version)),...activeVerifiedPlugins??[]]),services2=await createAgentSessionServices({cwd:cwd2,agentDir:agentDir2,settingsManager:runtimeSettingsManager,modelRuntimeSignal:AbortSignal.timeout(15e3),suite:parsed.suite,suiteAssembly:!0,...parsed.noPlugins||cliPluginSelection.profileId===void 0?{}:{pluginProfileId:cliPluginSelection.profileId},...parsed.noPlugins||cliPluginSelection.selectedPluginIds===void 0?{}:{selectedPluginIds:cliPluginSelection.selectedPluginIds},...parsed.noPlugins||cliPluginSelection.disabledPluginIds===void 0?{}:{disabledPluginIds:cliPluginSelection.disabledPluginIds},...parsed.noPlugins||pluginHost===void 0?{}:{pluginHost},...parsed.noPlugins||verifiedPlugins===void 0?{}:{verifiedPlugins},...parsed.noPlugins||options?.manifestOverrides===void 0?activeManifestOverrides===void 0?{}:{manifestOverrides:activeManifestOverrides}:{manifestOverrides:options.manifestOverrides},...parsed.noPlugins||activeInstalledCapabilityPlugins===void 0?{}:{installedCapabilityPlugins:activeInstalledCapabilityPlugins},...pluginBindingDiagnostics.length===0?{}:{pluginBindingDiagnostics},resourceLoaderOptions:{additionalSkillPaths:resolvedSkillPaths,additionalPromptTemplatePaths:resolvedPromptTemplatePaths,additionalThemePaths:resolvedThemePaths,noSkills:parsed.noSkills,noPromptTemplates:parsed.noPromptTemplates,noThemes:parsed.noThemes,noContextFiles:parsed.noContextFiles,systemPrompt:parsed.systemPrompt,appendSystemPrompt:[...parsed.appendSystemPrompt??[],...childProfile?.systemPromptAppend===void 0?[]:[childProfile.systemPromptAppend]]}}),{settingsManager:settingsManager2,modelRuntime:modelRuntime2}=services2,diagnostics=[...cliPluginSelection.diagnostics,...services2.diagnostics,...collectSettingsDiagnostics(settingsManager2)],modelPatterns=parsed.models??settingsManager2.getEnabledModels(),scopedModels=modelPatterns&&modelPatterns.length>0?await resolveModelScope(modelPatterns,modelRuntime2,{signal:AbortSignal.timeout(15e3)}):[],profileModel=childModelId===void 0?void 0:(()=>{let entry=scopedModels.find(candidate=>candidate.model.id===childModelId);if(entry===void 0){let available=scopedModels.map(candidate=>candidate.model.id).sort();throw new Error(`agent task child profile model ${JSON.stringify(childModelId)} is not among the runner's scoped models`+(available.length===0?" (none configured)":`; available: ${available.join(", ")}`))}return entry.model})(),sessionContext=sessionManager2.buildSessionContext(),{options:sessionOptions,cliThinkingFromModel,diagnostics:sessionOptionDiagnostics}=buildSessionOptions(parsed,scopedModels,sessionContext.messages.length>0,modelRuntime2,settingsManager2);diagnostics.push(...sessionOptionDiagnostics);let resumedSessionModel=(()=>{if(sessionOptions.model)return;let persisted=sessionContext.model;if(persisted)return modelRuntime2.getModel(persisted.provider,persisted.modelId)??void 0})();parsed.apiKey&&(sessionOptions.model?await modelRuntime2.setRuntimeApiKey(sessionOptions.model.provider,parsed.apiKey):diagnostics.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));let childProfileMode=childProfile!==void 0&&childProfile.mode==="readonly"&&parsed.subagentRunner===!0?"readonly":void 0,created=await createAgentSessionFromServices({services:services2,sessionManager:sessionManager2,model:profileModel??sessionOptions.model??resumedSessionModel,thinkingLevel:childProfile?.thinkingLevel??sessionOptions.thinkingLevel,scopedModels:sessionOptions.scopedModels,tools:sessionOptions.tools,excludeTools:sessionOptions.excludeTools,noTools:sessionOptions.noTools,customTools:sessionOptions.customTools,suite:sessionOptions.suite,discoverCapabilityPlugins:parsed.noPlugins?!1:void 0,traceEnabled:parsed.noTrace===!0?!1:void 0,...typeof process.env.OTEL_EXPORTER_OTLP_ENDPOINT=="string"&&process.env.OTEL_EXPORTER_OTLP_ENDPOINT.trim().length>0?{traceOptions:{otlp:{endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT.trim()}}}:{},hostLogger:processHostLogger,...childProfileMode===void 0?{}:{capabilityMode:childProfileMode},...subagentCommunicationWiring===void 0?{}:{subagentCommunicationWiring},subagentPoolFromSelfInvocation:!0,...appMode==="interactive"?{interactionHost:interactionHostSlots.interactive.host}:{},...appMode==="rpc"?{interactionHost:interactionHostSlots.rpc.host}:{}});for(let rejection of created.pluginRejections)diagnostics.push({type:"warning",message:`Capability plugin rejected (${rejection.code}): ${rejection.pluginId??rejection.manifestPath}: ${rejection.message}`});let cliThinkingOverride=parsed.thinking!==void 0||cliThinkingFromModel;if(created.session.model&&cliThinkingOverride&&created.session.setThinkingLevel(created.session.thinkingLevel),childProfile?.tools!==void 0){let narrowed=created.session.getActiveToolNames().filter(name=>childProfile.tools?.includes(name));created.session.setActiveToolsByName(narrowed)}return{...created,services:{...services2,observabilityGetMetricsRef:created.session.observabilityGetMetricsRef},diagnostics,...childProfile===void 0?{}:{childFacts:(()=>{let sessionApi=created.session.getSessionAPI(),systemPromptOptions=sessionApi.getSystemPromptOptions?.();return{activeTools:created.session.getActiveToolNames(),...childProfile?.thinkingLevel===void 0?{}:{thinkingLevel:sessionApi.getThinkingLevel?.()},...systemPromptOptions?.appendSystemPrompt===void 0?{}:{systemPromptAppend:systemPromptOptions.appendSystemPrompt},...created.session.model===void 0?{}:{model:{provider:created.session.model.provider,id:created.session.model.id,contextWindow:created.session.model.contextWindow,maxTokens:created.session.model.maxTokens,reasoning:created.session.model.reasoning}},capabilityMode:created.session.getCapabilityRuntime().host.mode}})()}}};time("createRuntime");function parseSubagentTaskChildProfile(raw){if(raw===void 0)return;let parsed2=parseAgentTaskChildProfileV1(raw);if(!parsed2.ok)throw new Error(`child task profile is invalid: ${parsed2.message}`);return parsed2.profile}if(parsed.subagentRunner===!0){let runnerSessionCwd=sessionManager.getCwd();await runSubagentTaskRunner({input:process.stdin,output:process.stdout,createSession:createSubagentTaskSessionFactoryV1({createSession:async request=>{let childProfile=parseSubagentTaskChildProfile(request.profile),resumeRead=typeof request.resumeSessionId=="string"&&request.resumeSessionId!==""?readAgentSession({agentDir,sessionId:request.resumeSessionId}):void 0;if(typeof request.resumeSessionId=="string"&&request.resumeSessionId!==""&&(resumeRead===void 0||request.parentSessionId===void 0||resumeRead.parentAgentSession!==request.parentSessionId))throw new Error(`resume target ${request.resumeSessionId} is not a persisted child of session ${String(request.parentSessionId)}`);let resumeFilePath=resumeRead!==void 0&&typeof request.resumeSessionId=="string"?findSessionFile2(agentSessionsDir2(agentDir),request.resumeSessionId):void 0,leafIdentity={current:void 0},requireIdentity=()=>{if(leafIdentity.current===void 0)throw new Error("leaf session identity is not bound yet");return leafIdentity.current},leafWiring=request.parentSessionId===void 0?{}:{postEscalate:text=>{createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).postEscalate(requireIdentity(),text)},sendSibling:(toSessionId,text)=>{createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).postSibling(requireIdentity(),toSessionId,text)},drainInbox:limit=>createSubagentMailbox({agentDir,ownerParentSessionId:()=>request.parentSessionId}).drainInbox(requireIdentity(),limit)},created=await createRuntime({cwd:runnerSessionCwd,agentDir,sessionManager:resumeFilePath!==void 0&&request.resumeSessionId!==void 0?SessionManager.open(resumeFilePath,agentSessionsDir2(agentDir),runnerSessionCwd):SessionManager.create(runnerSessionCwd,agentSessionsDir2(agentDir),{...request.parentSessionId===void 0?{}:{parentAgentSession:request.parentSessionId},...request.parentTraceId===void 0?{}:{parentTraceId:request.parentTraceId},...childProfile?.roleId===void 0?{}:{agentRole:childProfile.roleId}}),...childProfile===void 0?{}:{childProfile},...childProfile?.model===void 0?{}:{childModelId:childProfile.model},...Object.keys(leafWiring).length===0?{}:{subagentCommunicationWiring:leafWiring}}),session2=created.session,sessionApi=session2.getSessionAPI();return leafIdentity.current=sessionApi.getAgentSessionId?.()??sessionApi.getSessionId(),{prompt:text=>session2.prompt(text,{expandPromptTemplates:!1}),abort:reason=>session2.abort(reason),dispose:()=>session2.dispose(),getMessages:()=>sessionApi.getMessages(),getSessionId:()=>sessionApi.getSessionId(),onProgress:createTurnProgressSourceV1(session2),...sessionApi.steer===void 0?{}:{steer:text=>{let steerFn=sessionApi.steer;return steerFn===void 0?Promise.resolve():steerFn.call(sessionApi,text)}},...created.childFacts===void 0?{}:{facts:()=>created.childFacts}}}})}).done;return}let runtime,pendingSuiteSelector;try{runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager})}catch(error2){if(error2 instanceof SuiteRebindError&&(console.error(source_default.red(`Error: ${error2.message}`)),process.exit(1)),!(error2 instanceof SuiteResolutionError))throw error2;appMode!=="interactive"&&(console.error(source_default.red(`Error: ${error2.message}`)),process.exit(1)),pendingSuiteSelector={requestedId:error2.requestedId,available:error2.availableSuiteIds},parsed.suite=void 0,process.env[SUITE_ENV_VAR]===error2.requestedId&&delete process.env[SUITE_ENV_VAR];try{runtime=await createAgentSessionRuntime(createRuntime,{cwd:sessionManager.getCwd(),agentDir,sessionManager})}catch(retryError){throw retryError instanceof SuiteResolutionError&&(console.error(source_default.red(`Error: ${retryError.message}`)),process.exit(1)),retryError}}time("createAgentSessionRuntime");let{services,session,modelFallbackMessage}=runtime,{settingsManager,modelRuntime}=services;if(setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy),configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs()),parsed.help&&(reportDiagnostics(startupSettingsDiagnostics),printHelp(),process.exit(0)),parsed.listModels!==void 0){reportDiagnostics(startupSettingsDiagnostics);let searchPattern=typeof parsed.listModels=="string"?parsed.listModels:void 0;await listModels(modelRuntime,searchPattern,AbortSignal.timeout(15e3)),process.exit(0)}let stdinContent;appMode!=="rpc"&&(stdinContent=await readPipedStdin(),stdinContent!==void 0&&appMode==="interactive"&&(appMode="print")),time("readPipedStdin");let{initialMessage,initialImages}=await prepareInitialMessage(parsed,settingsManager.getImageAutoResize(),stdinContent);time("prepareInitialMessage"),initTheme(settingsManager.getTheme(),appMode==="interactive"),time("initTheme"),appMode==="interactive"&&deprecationWarnings.length>0&&await showDeprecationWarnings(deprecationWarnings),time("resolveModelScope");let allStartupDiagnostics=deduplicateDiagnostics([...startupSettingsDiagnostics,...runtime.diagnostics]),startupDiagnostics=filterAcknowledgedSuiteNotices(allStartupDiagnostics,settingsManager);await settingsManager.flush().catch(()=>{});let hasRuntimeErrors=runtime.diagnostics.some(diagnostic5=>diagnostic5.type==="error");if((appMode!=="interactive"||hasRuntimeErrors)&&reportDiagnostics(startupDiagnostics),hasRuntimeErrors&&process.exit(1),appMode==="interactive")for(let rejection of runtime.pluginRejections)console.error(source_default.yellow(`Warning: capability plugin rejected (${rejection.code}): ${rejection.pluginId??rejection.manifestPath}: ${rejection.message}`));time("createAgentSession");let noModelResolved=!session.model||session.model.provider==="unknown"&&session.model.id==="unknown";appMode!=="interactive"&&noModelResolved&&(console.error(source_default.red(modelFallbackMessage??formatNoModelsAvailableMessage())),process.exit(1));let startupBenchmark=isTruthyEnvFlag(process.env.AGENT_FORGE_STARTUP_BENCHMARK);if(startupBenchmark&&appMode!=="interactive"&&(console.error(source_default.red("Error: AGENT_FORGE_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!offlineMode&&appMode==="rpc"){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);modelRuntime.refresh({signal:controller.signal}).catch(()=>{}).finally(()=>clearTimeout(timeout))}if(appMode==="rpc")printTimings(),await runRpcMode(runtime,{interactionHostSlot:interactionHostSlots.rpc,getMetrics:options2=>runtime.observabilityGetMetricsRef?.current?.(options2)});else if(appMode==="interactive"){let interactiveMode=new InteractiveMode(runtime,{getMetrics:options2=>runtime.observabilityGetMetricsRef?.current?.(options2),migratedProviders,startupDiagnostics,modelFallbackMessage,initialMessage,initialImages,initialMessages:parsed.messages,verbose:parsed.verbose,tuiMode:parsed.tuiMode,initialThemeSetting:parsed.useTheme,pendingSuiteSelector,settingsManager});if(interactionHostSlots.interactive.setTarget(interactiveMode.createInteractionHostV1()),startupBenchmark){await interactiveMode.init(),time("interactiveMode.init"),await new Promise(resolve25=>setTimeout(resolve25,150)),interactiveMode.stop(),stopThemeWatcher(),printTimings(),process.stdout.writableLength>0&&await new Promise(resolve25=>process.stdout.once("drain",resolve25)),process.stderr.writableLength>0&&await new Promise(resolve25=>process.stderr.once("drain",resolve25));return}printTimings(),await interactiveMode.run()}else{printTimings();let exitCode=await runPrintMode(runtime,{mode:toPrintOutputMode(appMode),messages:parsed.messages,initialMessage,initialImages});stopThemeWatcher(),restoreStdout(),exitCode!==0&&(process.exitCode=exitCode);return}}export{getPackageDir,getReadmePath,getDocsPath,getExamplesPath,APP_NAME,CONFIG_DIR_NAME,VERSION,getAgentDir,getSessionsDir,configureHttpDispatcher,Text,Loader,CancellableLoader,Container,SelectList,Spacer,EXPERIMENTAL_PUBLIC_API_VERSION,LifecycleTransformError,LifecycleExecuteError,SUMMARY_MODEL_INVOCATION_ERROR_CODES,createDisposableRegistration,createEventEnvelope,detachedSessionSnapshot,parseCapabilityPluginManifest,MEMORY_RECALL_TOOL_NAME,dist_exports,parseArgs,resolveModelScopeWithDiagnostics,resolveCliModel,getShellConfig,getPowerShellConfig,sanitizeBinaryOutput,killProcessTree,readStoredCredential,CredentialSynchronizationError,ModelRuntime,convertToPng,resizeImage,formatDimensionNote,detectSupportedImageMimeTypeFromFile,stableJsonDigest,buildProfileIdentityV1,profileIdentitiesCompatible,PLUGIN_DISPOSE_EVENT_ID,PLUGIN_DISPOSE_EVENT_VERSION,PLUGIN_READY_EVENT_ID,PLUGIN_READY_EVENT_VERSION,SESSION_CONTEXT_REPLACED_EVENT_ID,SESSION_CONTEXT_REPLACED_EVENT_VERSION,SESSION_RELOAD_EVENT_ID,SESSION_RELOAD_EVENT_VERSION,MODEL_RESPONSE_EVENT_ID,MODEL_RESPONSE_EVENT_VERSION,MODEL_STREAM_EVENT_ID,MODEL_STREAM_EVENT_VERSION,TOOL_RESULT_EVENT_ID,TOOL_RESULT_EVENT_VERSION,TOOL_CALL_EVENT_ID,TOOL_CALL_EVENT_VERSION,TOOL_RESULT_RAW_EVENT_ID,TOOL_RESULT_RAW_EVENT_VERSION,TOOL_EXECUTE_EVENT_ID,TOOL_EXECUTE_EVENT_VERSION,TOOL_COMMIT_EVENT_ID,TOOL_COMMIT_EVENT_VERSION,OPERATION_END_EVENT_ID,OPERATION_END_EVENT_VERSION,validatePluginDisposeEventDataV1,validatePluginReadyEventDataV1,validateSessionContextReplacedEventDataV1,validateSessionReloadEventDataV1,validateModelResponseEventDataV1,validateModelStreamEventDataV1,validateToolResultEventDataV1,validateToolCallEventDataV1,validateToolExecuteEventDataV1,validateToolCommitEventDataV1,validateToolResultRawEventDataV1,TOOL_RESULT_TRANSFORM_EVENT_ID,TOOL_RESULT_TRANSFORM_EVENT_VERSION,validateToolResultTransformEventDataV1,validateOperationEndEventDataV1,CAPABILITY_CALL_EVENT_ID,CAPABILITY_CALL_EVENT_VERSION,validateCapabilityCallEventDataV1,OPERATION_START_EVENT_ID,OPERATION_START_EVENT_VERSION,OPERATION_STEP_EVENT_ID,OPERATION_STEP_EVENT_VERSION,validateOperationStartEventDataV1,validateOperationStepEventDataV1,OPERATION_CANCEL_EVENT_ID,OPERATION_CANCEL_EVENT_VERSION,validateOperationCancelEventDataV1,discoverCapabilityPluginManifests,loadCapabilityPlugin,loadCapabilityPluginSync,loadCapabilityPluginFromManifest,ecosystem_exports,assembleProfile,replaceProfilePlugin,listBuiltinPluginProfilesV1,listBuiltinPluginManifestsV1,resolveBuiltinPluginProfileV1,plugin_manager_controller_exports,DurableServiceErrorV1,durableLogPath,createFileDurableStoreBackend,createDurableService,projectSessionTranscript,CodingAgentSessionRuntime,CodingAgentServerService,assembleCodingAgentServer,DEFAULT_SUITE_ID,isBuiltinSuiteId,buildResolvedAgentProfileV1,parseFrontmatter,stripFrontmatter,createSyntheticSourceInfo,loadSkillsFromDir,formatSkillsForPrompt,loadSkills,createProfileLock,verifyProfileLock,replaceProfileLock,createProfileRegistry,SuiteResolutionError,listSuiteIds,BOOTSTRAP_LIFECYCLE_PLUGIN_ID,SESSION_COMPACTION_COMMIT_EVENT_ID,SESSION_COMPACTION_COMMIT_EVENT_VERSION,validateSessionCompactionCommitEventDataV1,installBootstrapLifecycle,defineTool,AgentCompositionRuntime,createAgentCompositionRuntime,convertToLlm2 as convertToLlm,SessionHeaderScanLimitError,FileSessionStorageProvider,CURRENT_SESSION_VERSION,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext2 as buildSessionContext,SessionManager,serializeConversation2 as serializeConversation,DEFAULT_COMPACTION_SETTINGS2 as DEFAULT_COMPACTION_SETTINGS,calculateContextTokens2 as calculateContextTokens,getLastAssistantUsage2 as getLastAssistantUsage,shouldCompact2 as shouldCompact,estimateTokens2 as estimateTokens,findTurnStartIndex2 as findTurnStartIndex,findCutPoint2 as findCutPoint,generateSummary2 as generateSummary,generateSummaryWithUsage2 as generateSummaryWithUsage,compact2 as compact,collectEntriesForBranchSummary2 as collectEntriesForBranchSummary,prepareBranchEntries2 as prepareBranchEntries,generateBranchSummary2 as generateBranchSummary,BOOTSTRAP_COMPACTION_PLUGIN_ID,DEFAULT_COMPACTION_POLICY_NAME,installBootstrapCompactionPolicy,BOOTSTRAP_RETRY_PLUGIN_ID,DEFAULT_RETRY_POLICY_NAME,installBootstrapRetryPolicy,Theme,getAvailableThemes,initTheme,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,keyText,keyHint,rawKeyHint,truncateToVisualLines,DEFAULT_MAX_LINES2 as DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES3 as DEFAULT_MAX_BYTES,formatSize2 as formatSize,truncateHead2 as truncateHead,truncateTail2 as truncateTail,truncateLine,createLocalBashOperations,createBashToolDefinition,createBashTool2 as createBashTool,renderDiff,generateUnifiedPatch2 as generateUnifiedPatch,generateDiffString2 as generateDiffString,withFileMutationQueue2 as withFileMutationQueue,createEditToolDefinition,createEditTool2 as createEditTool,createFindToolDefinition,createFindTool,createGrepToolDefinition,createGrepTool,createLsToolDefinition,createLsTool,createLocalPowerShellOperations,createPowerShellToolDefinition,createPowerShellTool,createReadToolDefinition,createReadTool2 as createReadTool,createWriteToolDefinition,createWriteTool2 as createWriteTool,createCodingTools,createReadOnlyTools,BOOTSTRAP_TOOLS_PLUGIN_ID,installBootstrapTools,installSessionBootstrapTools,resolvePluginCapabilityOrder,validateExecutionFactsV1,validateRetryScheduleV1,createCapabilityRuntime,parseSkillBlock,AgentSession,DefaultPackageManager,SettingsManager,loadProjectContextFiles,DefaultResourceLoader,createAgentSessionServices,createAgentSessionFromServices,AgentSessionRuntime,createAgentSessionRuntime,createAgentSession,createStableAgentSession,createStableAgentSessionRuntime,createFileSessionSource,startCodingAgentRemoteServer,DynamicBorder,SessionSelectorComponent,DialogInputComponent,DialogSelectorComponent,createProfileMigrationPolicy,SUITE_DELETE_CONFIRM_TOKEN,SuiteLifecycleError,createSuite,findSuiteSessionRefs,deleteSuite,resetSuite,clearDanglingSuiteSettings,copyToClipboard,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CustomEditor,CustomMessageComponent,FooterComponent,SettingsSelectorComponent,SkillInvocationMessageComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,LoginDialogComponent,OAuthSelectorComponent,DialogEditorComponent,ModelSelectorComponent,ThinkingSelectorComponent,UserMessageSelectorComponent,InteractiveMode,createStdioChannelAdapter,createHostOutputProjector,runPrintMode,RpcClient,runRpcMode,PluginManagerEntryComponent,plugin_selection_controller_exports,main};