@ai-agent-forge/agent-forge 0.86.1 → 0.86.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/bundle/.build-manifest.json +12 -12
- package/dist/bundle/chunks/{chunk-S3YLY4MG.js → chunk-JR3Q27QP.js} +4 -4
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session-compaction.d.ts +5 -0
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +19 -1
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-internal.d.ts +6 -0
- package/dist/core/agent-session-internal.d.ts.map +1 -1
- package/dist/core/agent-session-internal.js.map +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +13 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +1 -1
- package/dist/core/extensions/bootstrap-compaction-policy.js +3 -1
- package/dist/core/extensions/bootstrap-compaction-policy.js.map +1 -1
- package/dist/core/extensions/microcompact.d.ts +3 -2
- package/dist/core/extensions/microcompact.d.ts.map +1 -1
- package/dist/core/extensions/microcompact.js +14 -5
- package/dist/core/extensions/microcompact.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +4 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/package.json +1 -1
|
@@ -726,7 +726,7 @@ Additional focus: ${customInstructions}`:instructions=BRANCH_SUMMARY_PROMPT;let
|
|
|
726
726
|
${conversationText}
|
|
727
727
|
</conversation>
|
|
728
728
|
|
|
729
|
-
${instructions}`,maxTokens=Math.min(4096,model.maxTokens>0?model.maxTokens:Number.POSITIVE_INFINITY),result=await invocation.invoke({version:1,systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,prompt:promptText,maxTokens},signal);if(result.status==="aborted")return{aborted:!0};if(result.status==="failed")return{error:result.error.code===SUMMARY_MODEL_INVOCATION_ERROR_CODES.transportError?result.error.message:formatSummaryFailure("Branch summarization",result.error)};let summary=BRANCH_SUMMARY_PREAMBLE+result.text,{readFiles,modifiedFiles}=computeFileLists2(fileOps);return summary+=formatFileOperations2(readFiles,modifiedFiles),{summary:summary||"No summary generated",usage:result.usage,readFiles,modifiedFiles}}var MICROCOMPACT_CUSTOM_TYPE="microcompact.v1",MICROCOMPACT_ELIDED_PLACEHOLDER="[earlier tool result elided by microcompact]",DEFAULT_MIN_ELIDE_CHARS=200,MIN_MICROCOMPACT_FREED_TOKENS=2048;function isElidableToolResult(message,minChars){return message.role!=="toolResult"?!1:contentText(message.content,"").length>=minChars}function planMicrocompact(pathEntries,settings2,options={}){let minChars=options.minElideChars??DEFAULT_MIN_ELIDE_CHARS,accumulated=0,cutIndex=0;for(let i=pathEntries.length-1;i>=0;i--){let entry=pathEntries[i],messageTokens=entry.message?estimateTokens2(entry.message):0;if(messageTokens!==0&&(accumulated+=messageTokens,accumulated>=settings2.keepRecentTokens)){cutIndex=i;break}}let freedTokens=0,elidedCount=0;for(let i=0;i<cutIndex;i++){let message=pathEntries[i].message;!message||!isElidableToolResult(message,minChars)||(freedTokens+=estimateTokens2(message)-estimateTokens2({...message,content:[{type:"text",text:MICROCOMPACT_ELIDED_PLACEHOLDER}]}),elidedCount+=1)}let elideBefore=pathEntries[cutIndex];if(elidedCount===0||freedTokens<MIN_MICROCOMPACT_FREED_TOKENS)return;let elideBeforeEntryId=elideBefore?.id;if(elideBeforeEntryId)return{elideBeforeEntryId,freedTokens,elidedCount}}function lastMicrocompactMarker(pathEntries){let marker;for(let entry of pathEntries){if(entry.type!=="custom"||entry.customType!==MICROCOMPACT_CUSTOM_TYPE)continue;let data=entry.data;typeof data?.elideBeforeEntryId=="string"&&(marker={elideBeforeEntryId:data.elideBeforeEntryId,minChars:typeof data.minChars=="number"&&data.minChars>=0?data.minChars:DEFAULT_MIN_ELIDE_CHARS})}return marker}function applyMicrocompactElision(path15){let marker=lastMicrocompactMarker(path15);if(marker===void 0)return path15;let cutIndex=path15.findIndex(entry=>entry.id===marker.elideBeforeEntryId);return cutIndex<=0?path15:path15.map((entry,index3)=>{if(index3>=cutIndex||entry.type!=="message")return entry;let message=entry.message;return message.role!=="toolResult"||contentText(message.content,"").length<marker.minChars?entry:{...entry,message:{...message,content:[{type:"text",text:MICROCOMPACT_ELIDED_PLACEHOLDER}]}}})}var BOOTSTRAP_COMPACTION_PLUGIN_ID="agent-forge.bootstrap-compaction",DEFAULT_COMPACTION_POLICY_NAME="default";function installBootstrapCompactionPolicy(runtime){return loadCapabilityPluginSync(runtime,{id:BOOTSTRAP_COMPACTION_PLUGIN_ID,version:"0.0.0",apiVersion:EXPERIMENTAL_PUBLIC_API_VERSION,entry:"<embedded:bootstrap-compaction>",requiredCapabilities:["compaction-policy"]},api=>{api.registerEntryProjection({customType:MICROCOMPACT_CUSTOM_TYPE,project:entries=>applyMicrocompactElision(entries)}),api.registerCompactionPolicy(DEFAULT_COMPACTION_POLICY_NAME,{prepare:request=>prepareCompaction2(request.entries,request.settings),decide:request=>{if(!request.enabled)return{compact:!1};if(request.reason==="threshold"){let usage=request.contextUsage,overBudget=usage!==void 0&&usage.contextWindow>0&&usage.contextTokens>usage.contextWindow-usage.reserveTokens;if(overBudget&&request.branchEntries!==void 0){let plan=planMicrocompact(request.branchEntries,{enabled:!0,reserveTokens:usage.reserveTokens,keepRecentTokens:request.keepRecentTokens??0});if(plan)return{compact:!1,relief:{customType:MICROCOMPACT_CUSTOM_TYPE,data:{elideBeforeEntryId:plan.elideBeforeEntryId,minChars:DEFAULT_MIN_ELIDE_CHARS}}}}return{compact:overBudget,retry:!1}}return request.recoveryAttempted?{compact:!1,failureMessage:request.contextOverflow?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt."}:{compact:request.contextOverflow||request.recoverableLength,retry:request.canContinue}},summarize:async request=>compact2(request.preparation,{invocation:request.invocation,model:request.model,customInstructions:request.customInstructions,thinkingLevel:request.thinkingLevel,signal:request.signal})})})}var BOOTSTRAP_RETRY_PLUGIN_ID="agent-forge.bootstrap-retry",DEFAULT_RETRY_POLICY_NAME="default";function installBootstrapRetryPolicy(runtime){return loadCapabilityPluginSync(runtime,{id:BOOTSTRAP_RETRY_PLUGIN_ID,version:"0.0.0",apiVersion:EXPERIMENTAL_PUBLIC_API_VERSION,entry:"<embedded:bootstrap-retry>",requiredCapabilities:["retry-policy"]},api=>{api.registerRetryPolicy(DEFAULT_RETRY_POLICY_NAME,{classify:({message})=>{if(!message||typeof message!="object")throw new Error("Retry classification requires an assistant message object");return isRetryableAssistantError(message)},decide:({retryable,enabled,attempt:attempt2,maxAttempts,baseDelayMs})=>({retry:enabled&&retryable&&attempt2<=maxAttempts,delayMs:baseDelayMs*2**Math.max(0,attempt2-1)})})})}import*as fs4 from"node:fs";import*as path8 from"node:path";function M(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=M();function N(l3){T=l3}var _={exec:()=>null};function E(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Te=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:E(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:E(l3=>new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}>`))},Oe=/^(?:[ \t]*(?:\n|$))+/,we=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,B=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Se=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),F=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,$e=/^[^\n]+/,U=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Le=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_e=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ze=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",K).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=d(F).replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Me=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),W={blockquote:Me,code:we,def:Le,fences:ye,heading:Pe,hr:B,html:ze,lheading:ae,list:_e,newline:Oe,paragraph:le,table:_,text:$e},se=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ee={...W,lheading:Se,table:se,paragraph:d(F).replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},Ie={...W,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:_,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(F).replace("hr",B).replace("heading",` *#{1,6} *[^
|
|
729
|
+
${instructions}`,maxTokens=Math.min(4096,model.maxTokens>0?model.maxTokens:Number.POSITIVE_INFINITY),result=await invocation.invoke({version:1,systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,prompt:promptText,maxTokens},signal);if(result.status==="aborted")return{aborted:!0};if(result.status==="failed")return{error:result.error.code===SUMMARY_MODEL_INVOCATION_ERROR_CODES.transportError?result.error.message:formatSummaryFailure("Branch summarization",result.error)};let summary=BRANCH_SUMMARY_PREAMBLE+result.text,{readFiles,modifiedFiles}=computeFileLists2(fileOps);return summary+=formatFileOperations2(readFiles,modifiedFiles),{summary:summary||"No summary generated",usage:result.usage,readFiles,modifiedFiles}}var MICROCOMPACT_CUSTOM_TYPE="microcompact.v1",MICROCOMPACT_ELIDED_PLACEHOLDER="[earlier tool result elided by microcompact]",DEFAULT_MIN_ELIDE_CHARS=200,MIN_MICROCOMPACT_FREED_TOKENS=2048;function isElidableToolResult(message,minChars){return message.role!=="toolResult"||Array.isArray(message.content)&&message.content.some(part=>part.type!=="text")?!1:contentText(message.content,"").length>=minChars}function planMicrocompact(pathEntries,settings2,options={}){if(!settings2.enabled)return;let minChars=options.minElideChars??DEFAULT_MIN_ELIDE_CHARS,accumulated=0,cutIndex=0;for(let i=pathEntries.length-1;i>=0;i--){let entry=pathEntries[i],messageTokens=entry.message?estimateTokens2(entry.message):0;if(messageTokens!==0&&(accumulated+=messageTokens,accumulated>=settings2.keepRecentTokens)){cutIndex=i;break}}let freedTokens=0,elidedCount=0;for(let i=0;i<cutIndex;i++){let message=pathEntries[i].message;!message||!isElidableToolResult(message,minChars)||(freedTokens+=estimateTokens2(message)-estimateTokens2({...message,content:[{type:"text",text:MICROCOMPACT_ELIDED_PLACEHOLDER}]}),elidedCount+=1)}let elideBefore=pathEntries[cutIndex];if(elidedCount===0||freedTokens<MIN_MICROCOMPACT_FREED_TOKENS)return;let elideBeforeEntryId=elideBefore?.id;if(elideBeforeEntryId)return{elideBeforeEntryId,freedTokens,elidedCount}}function lastMicrocompactMarker(pathEntries){let marker;for(let entry of pathEntries){if(entry.type!=="custom"||entry.customType!==MICROCOMPACT_CUSTOM_TYPE)continue;let data=entry.data;typeof data?.elideBeforeEntryId=="string"&&(marker={elideBeforeEntryId:data.elideBeforeEntryId,minChars:typeof data.minChars=="number"&&data.minChars>=0?data.minChars:DEFAULT_MIN_ELIDE_CHARS})}return marker}function applyMicrocompactElision(path15){let marker=lastMicrocompactMarker(path15);if(marker===void 0)return path15;let cutIndex=path15.findIndex(entry=>entry.id===marker.elideBeforeEntryId);return cutIndex<=0?path15:path15.map((entry,index3)=>{if(index3>=cutIndex||entry.type!=="message")return entry;let message=entry.message;return isElidableToolResult(message,marker.minChars)?{...entry,message:{...message,content:[{type:"text",text:MICROCOMPACT_ELIDED_PLACEHOLDER}]}}:entry})}var BOOTSTRAP_COMPACTION_PLUGIN_ID="agent-forge.bootstrap-compaction",DEFAULT_COMPACTION_POLICY_NAME="default";function installBootstrapCompactionPolicy(runtime){return loadCapabilityPluginSync(runtime,{id:BOOTSTRAP_COMPACTION_PLUGIN_ID,version:"0.0.0",apiVersion:EXPERIMENTAL_PUBLIC_API_VERSION,entry:"<embedded:bootstrap-compaction>",requiredCapabilities:["compaction-policy"]},api=>{api.registerEntryProjection({customType:MICROCOMPACT_CUSTOM_TYPE,project:entries=>applyMicrocompactElision(entries)}),api.registerCompactionPolicy(DEFAULT_COMPACTION_POLICY_NAME,{prepare:request=>prepareCompaction2(request.entries,request.settings),decide:request=>{if(!request.enabled)return{compact:!1};if(request.reason==="threshold"){let usage=request.contextUsage,overBudget=usage!==void 0&&usage.contextWindow>0&&usage.contextTokens>usage.contextWindow-usage.reserveTokens;if(overBudget&&request.branchEntries!==void 0){let plan=planMicrocompact(request.branchEntries,{enabled:request.microcompactEnabled!==!1,reserveTokens:usage.reserveTokens,keepRecentTokens:request.keepRecentTokens??0});if(plan)return{compact:!1,relief:{customType:MICROCOMPACT_CUSTOM_TYPE,data:{elideBeforeEntryId:plan.elideBeforeEntryId,minChars:DEFAULT_MIN_ELIDE_CHARS}}}}return{compact:overBudget,retry:!1}}return request.recoveryAttempted?{compact:!1,failureMessage:request.contextOverflow?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt."}:{compact:request.contextOverflow||request.recoverableLength,retry:request.canContinue}},summarize:async request=>compact2(request.preparation,{invocation:request.invocation,model:request.model,customInstructions:request.customInstructions,thinkingLevel:request.thinkingLevel,signal:request.signal})})})}var BOOTSTRAP_RETRY_PLUGIN_ID="agent-forge.bootstrap-retry",DEFAULT_RETRY_POLICY_NAME="default";function installBootstrapRetryPolicy(runtime){return loadCapabilityPluginSync(runtime,{id:BOOTSTRAP_RETRY_PLUGIN_ID,version:"0.0.0",apiVersion:EXPERIMENTAL_PUBLIC_API_VERSION,entry:"<embedded:bootstrap-retry>",requiredCapabilities:["retry-policy"]},api=>{api.registerRetryPolicy(DEFAULT_RETRY_POLICY_NAME,{classify:({message})=>{if(!message||typeof message!="object")throw new Error("Retry classification requires an assistant message object");return isRetryableAssistantError(message)},decide:({retryable,enabled,attempt:attempt2,maxAttempts,baseDelayMs})=>({retry:enabled&&retryable&&attempt2<=maxAttempts,delayMs:baseDelayMs*2**Math.max(0,attempt2-1)})})})}import*as fs4 from"node:fs";import*as path8 from"node:path";function M(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=M();function N(l3){T=l3}var _={exec:()=>null};function E(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Te=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:E(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:E(l3=>new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:E(l3=>new RegExp(`^ {0,${l3}}>`))},Oe=/^(?:[ \t]*(?:\n|$))+/,we=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,B=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Se=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),F=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,$e=/^[^\n]+/,U=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Le=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_e=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ze=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",K).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=d(F).replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Me=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),W={blockquote:Me,code:we,def:Le,fences:ye,heading:Pe,hr:B,html:ze,lheading:ae,list:_e,newline:Oe,paragraph:le,table:_,text:$e},se=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ee={...W,lheading:Se,table:se,paragraph:d(F).replace("hr",B).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},Ie={...W,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:_,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(F).replace("hr",B).replace("heading",` *#{1,6} *[^
|
|
730
730
|
]`).replace("lheading",ae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ae=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ce=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ue=/^( {2,}|\\)\n(?!\s*$)/,Be=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,I=/[\p{P}\p{S}]/u,Z=/[\s\p{P}\p{S}]/u,X=/[^\s\p{P}\p{S}]/u,De=d(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Z).getRegex(),pe=/(?!~)[\p{P}\p{S}]/u,qe=/(?!~)[\s\p{P}\p{S}]/u,ve=/(?:[^\s\p{P}\p{S}]|~)/u,He=d(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Te?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ze=d(ce,"u").replace(/punct/g,I).getRegex(),Ge=d(ce,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ne=d(he,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Qe=d(he,"gu").replace(/notPunctSpace/g,ve).replace(/punctSpace/g,qe).replace(/punct/g,pe).getRegex(),je=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Fe=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,I).getRegex(),Ue="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ke=d(Ue,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),We=d(/\\(punct)/,"gu").replace(/punct/g,I).getRegex(),Xe=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Je=d(K).replace("(?:-->|$)","-->").getRegex(),Ve=d("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Je).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),v=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ye=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",v).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=d(/^!?\[(label)\]\[(ref)\]/).replace("label",v).replace("ref",U).getRegex(),de=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),et=d("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",de).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,J={_backpedal:_,anyPunctuation:We,autolink:Xe,blockSkip:He,br:ue,code:Ce,del:_,delLDelim:_,delRDelim:_,emStrongLDelim:Ze,emStrongRDelimAst:Ne,emStrongRDelimUnd:je,escape:Ae,link:Ye,nolink:de,punctuation:De,reflink:ke,reflinkSearch:et,tag:Ve,text:Be,url:_},tt={...J,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",v).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",v).getRegex()},Q={...J,emStrongRDelimAst:Qe,emStrongLDelim:Ge,delLDelim:Fe,delRDelim:Ke,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ie).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ie).getRegex()},nt={...Q,br:d(ue).replace("{2,}","*").getRegex(),text:d(Q.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},D={normal:W,gfm:Ee,pedantic:Ie},A={normal:J,gfm:Q,breaks:nt,pedantic:tt},rt={"&":"&","<":"<",">":">",'"':""","'":"'"},ge=l3=>rt[l3];function O(l3,e){if(e){if(m.escapeTest.test(l3))return l3.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l3))return l3.replace(m.escapeReplaceNoEncode,ge);return l3}function V(l3){try{l3=encodeURI(l3).replace(m.percentDecode,"%")}catch{return null}return l3}function Y(l3,e){let t=l3.replace(m.findPipe,(r,i,o)=>{let u=!1,a=i;for(;--a>=0&&o[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,"|");return n}function $(l3,e,t){let n=l3.length;if(n===0)return"";let s=0;for(;s<n;){let r=l3.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l3.slice(0,n-s)}function ee(l3){let e=l3.split(`
|
|
731
731
|
`),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
|
|
732
732
|
`)}function fe(l3,e){if(l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function me(l3,e=0){let t=e,n="";for(let s of l3)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function xe(l3,e,t,n,s){let r=e.href,i=e.title||null,o=l3[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let u={type:l3[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:i,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,u}function st(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
|
|
@@ -982,7 +982,7 @@ ${getProviderLoginHelp()}
|
|
|
982
982
|
|
|
983
983
|
Then use /model to select a model.`}function formatNoApiKeyFoundMessage(provider){return`No API key found for ${provider===UNKNOWN_PROVIDER?"the selected model":provider}.
|
|
984
984
|
|
|
985
|
-
${getProviderLoginHelp()}`}function withoutDeletedHeaders(headers){return headers?Object.fromEntries(Object.entries(headers).filter(entry=>entry[1]!==null)):void 0}function estimateMessagesTokens(messages){let tokens=0;for(let message of messages)tokens+=estimateTokens2(message);return tokens}var OVERFLOW_TRIM_MAX_STAGES=3,OVERFLOW_TRIM_STAGE2_TARGET_TOKENS=1e4;function overflowTrimFailureMessage(attempts,failureMessage){return attempts>0?`Context overflow persists after compaction and ${attempts} trim attempts. ${failureMessage}`:failureMessage}function trimOverflowProjection(messages,stage,keepRecentTokens){if(stage>=2){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="user")return i===0?messages:messages.slice(i);for(let i=messages.length-1;i>=0;i--)if(isTurnStartMessage(messages[i]))return i===0?messages:messages.slice(i);return messages}let target=stage===0?keepRecentTokens:OVERFLOW_TRIM_STAGE2_TARGET_TOKENS,turnStarts=[];for(let i=0;i<messages.length;i++)isTurnStartMessage(messages[i])&&turnStarts.push(i);if(turnStarts.length===0)return messages;let suffixTokens=new Array(messages.length+1).fill(0);for(let i=messages.length-1;i>=0;i--)suffixTokens[i]=suffixTokens[i+1]+estimateTokens2(messages[i]);if(suffixTokens[0]<=target)return messages;for(let start of turnStarts)if(suffixTokens[start]<=target)return messages.slice(start);let floorStart=turnStarts[turnStarts.length-1];return floorStart===0?messages:messages.slice(floorStart)}async function getRequiredRequestAuth(session,model){let result;try{result=await session._modelRuntime.getAuth(model)}catch(error2){let cause=error2 instanceof Error?error2.cause:void 0;throw cause instanceof Error&&cause.message==="authHeader requires a resolved API key"?new Error(formatNoApiKeyFoundMessage(model.provider)):error2}if(result&&(result.auth.apiKey||result.auth.headers))return{model:result.auth.baseUrl?{...model,baseUrl:result.auth.baseUrl}:model,apiKey:result.auth.apiKey,headers:withoutDeletedHeaders(result.auth.headers),env:result.env};throw session._modelRuntime.isUsingOAuth(model.provider)?new Error(`Authentication failed for "${model.provider}". Credentials may have expired or network is unavailable. Run '/login ${model.provider}' to re-authenticate.`):new Error(formatNoApiKeyFoundMessage(model.provider))}async function getSummarizationRequestAuth(session,model){if(session.agent.streamFunction===streamSimple)return getRequiredRequestAuth(session,model);try{let result=await session._modelRuntime.getAuth(model);return result?{model:result.auth.baseUrl?{...model,baseUrl:result.auth.baseUrl}:model,apiKey:result.auth.apiKey,headers:withoutDeletedHeaders(result.auth.headers),env:result.env}:{model}}catch{return{model}}}function summaryModelFacts(model){return{id:model.id,contextWindow:model.contextWindow,maxTokens:model.maxTokens,reasoning:model.reasoning}}function createSummaryModelInvocationV1(session,auth,retry,callbacks,options={}){return{invoke:async(input,signal)=>{let maxTokens=input.maxTokens===void 0||auth.model.maxTokens<=0?input.maxTokens:Math.min(input.maxTokens,auth.model.maxTokens),requestOptions={...maxTokens===void 0?{}:{maxTokens},signal,apiKey:auth.apiKey,headers:auth.headers,env:auth.env,cacheRetention:"none",sessionId:options.routingSessionId??uuidv7()};auth.model.reasoning&&input.thinkingLevel&&input.thinkingLevel!=="off"&&(requestOptions.reasoning=input.thinkingLevel);let context={systemPrompt:input.systemPrompt,messages:[{role:"user",content:[{type:"text",text:input.prompt}],timestamp:Date.now()}]},produce=async()=>{let streamFn=session.agent.streamFunction;return streamFn?(await streamFn(auth.model,context,requestOptions)).result():completeSimple(auth.model,context,requestOptions)},response2;try{response2=await retryAssistantCall(produce,retry,requestOptions.signal,callbacks)}catch(error2){return error2 instanceof Error&&error2.name==="AbortError"?{version:1,status:"aborted"}:{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.transportError,message:error2 instanceof Error?error2.message:String(error2)}}}return response2.stopReason==="aborted"?{version:1,status:"aborted"}:response2.stopReason==="error"?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.providerError,message:response2.errorMessage||"Unknown error"}}:response2.stopReason==="length"?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.lengthCap,message:"generation hit the token cap and the summary is incomplete"}}:response2.content.some(block=>block.type==="toolCall")?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.toolCall,message:"attempted to call a tool"}}:{version:1,status:"completed",text:contentText(response2.content),usage:response2.usage}}}}async function compactBeforeNextAssistantResponse(session,context,signal){let model=session.model,settings2=session.settingsManager.getCompactionSettings();if(!model||model.contextWindow<=0)return context;let contextTokens=estimateContextTokens2(context.messages).tokens,decision=await decideCompaction(session,{reason:"threshold",contextOverflow:!1,recoverableLength:!1,contextUsage:{contextTokens,contextWindow:model.contextWindow,reserveTokens:settings2.reserveTokens},canContinue:!1,signal:signal??session._policyDecisionAbortController?.signal});return await dispatchCompactionDecisionLifecycle(session,{reason:"threshold",compact:decision.compact,willRetry:!1,contextTokens,contextWindow:model.contextWindow,reserveTokens:settings2.reserveTokens,...decision.failureMessage===void 0?{}:{failureMessage:decision.failureMessage}}),decision.compact?(await session._runAutoCompaction("threshold",!1),{...context,messages:session.agent.state.messages.slice()}):context}function executionFacts(session,phase,operationId,revision){let inputRevision=detachedSessionSnapshot(revision??session.sessionManager.getRevision());return Object.freeze({version:1,operationId:operationId??`${phase}:${inputRevision.sessionId}:${inputRevision.sequence}:${inputRevision.leafId??"root"}`,sessionId:session.sessionId,inputRevision,phase})}async function runCompactionSummary(session,preparation,auth,customInstructions,signal,reason,execution){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let result=await runtime.summarizeCompaction(session._compactionPolicyName,{preparation,model:summaryModelFacts(auth.model),invocation:createSummaryModelInvocationV1(session,auth,summarizationRetryPolicy(session,execution.operationId,execution.inputRevision,signal),summarizationRetryCallbacks(session,{source:"compaction",reason}),{routingSessionId:session.sessionId}),customInstructions,signal,reason,thinkingLevel:session.thinkingLevel==="off"?"off":"low",sessionId:session.sessionId,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution});return{...result,usage:result.usage}}async function decideCompaction(session,input){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return session._compactionPolicyName===DEFAULT_COMPACTION_POLICY_NAME&&!runtime.hasCompactionPolicy(session._compactionPolicyName)?(session._hostLogger?.warn("compaction","no compaction policy registered; skipping automatic compaction",{fields:{policyName:session._compactionPolicyName,reason:input.reason}}),{compact:!1,retry:!1}):runtime.decideCompaction(session._compactionPolicyName,{enabled:session.settingsManager.getCompactionSettings().enabled,recoveryAttempted:session._overflowRecoveryAttempted,...input,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution:input.execution??executionFacts(session,"compaction"),signal:input.signal})}async function prepareCompaction3(session,pathEntries,settings2,execution,signal){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let preparation=await runtime.prepareCompaction(session._compactionPolicyName,{entries:pathEntries,settings:settings2,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution:execution??executionFacts(session,"compaction"),signal});if(preparation===void 0)return;let value=preparation;if(!preparation||typeof preparation!="object"||typeof value.firstKeptEntryId!="string"||!Array.isArray(value.messagesToSummarize)||!Array.isArray(value.turnPrefixMessages)||typeof value.isSplitTurn!="boolean"||!Number.isFinite(value.tokensBefore)||typeof value.fileOps!="object"||typeof value.settings!="object")throw new Error(`Compaction policy returned an invalid preparation: ${session._compactionPolicyName}`);return preparation}function captureCompactionCommitBoundary(session,reason){let pathEntries=session.sessionManager.getBranch(),expectedRevision=session.sessionManager.getRevision();return{pathEntries,expectedRevision,operationId:`compaction:${reason}:${expectedRevision.sessionId}:${expectedRevision.sequence}:${expectedRevision.leafId??"root"}`}}function enqueueCompaction(session,operation){let previous=session._compactionQueue,release;session._compactionQueue=new Promise(resolve25=>{release=resolve25});let queued=previous.then(()=>{if(session._reloadInProgress)throw new Error("Session reload in progress; compaction was not started");return operation()}).finally(release);return session._activeCompactionPromise=queued,queued.then(()=>{session._activeCompactionPromise===queued&&(session._activeCompactionPromise=void 0)},()=>{session._activeCompactionPromise===queued&&(session._activeCompactionPromise=void 0)}),queued}function commitCompaction(session,input){let commit=session.sessionManager.commitCompaction({version:1,operationId:input.operationId,expectedRevision:input.expectedRevision,summary:input.summary,firstKeptEntryId:input.firstKeptEntryId,tokensBefore:input.tokensBefore,details:input.details,fromHook:!1,usage:input.usage});if(commit.status==="revision_conflict")throw new Error(`Compaction commit revision conflict: expected ${input.expectedRevision.sequence}/${input.expectedRevision.leafId??"root"}, current ${commit.currentRevision.sequence}/${commit.currentRevision.leafId??"root"}`);let entry=session.sessionManager.getEntry(commit.entryId);if(entry?.type!=="compaction"||entry.operationId!==input.operationId)throw new Error(`Compaction commit entry is unavailable: ${commit.entryId}`);return{entry,status:commit.status,revision:commit.revision}}async function dispatchCompactionCommitLifecycle(session,reason,commit){try{let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let entry=commit.entry,data={version:1,status:commit.status,entryId:entry.id,operationId:entry.operationId??"",revision:commit.revision,reason,summary:entry.summary,firstKeptEntryId:entry.firstKeptEntryId,tokensBefore:entry.tokensBefore,fromHook:entry.fromHook===!0,...entry.usage===void 0?{}:{usage:entry.usage},...entry.details===void 0?{}:{details:entry.details}},delivery=await runtime.dispatchLifecycle({type:SESSION_COMPACTION_COMMIT_EVENT_ID,version:SESSION_COMPACTION_COMMIT_EVENT_VERSION,phase:"committed",data,operationId:entry.operationId,source:"agent-session"});for(let failure2 of delivery.report.failures)session._observeLifecycleDeliveryError(failure2.error,failure2.pluginId,`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}/${failure2.kind}`)}catch(error2){let report=error2.report;if(report?.failures)for(let failure2 of report.failures)session._observeLifecycleDeliveryError(failure2.error,failure2.pluginId,`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}/${failure2.kind}`);else session._observeLifecycleDeliveryError(error2,"<capability-lifecycle>",`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}`)}}async function decideOverflow(session,message,execution,signal){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return runtime.decideOverflow(session._overflowPolicyName,{message,contextWindow:session.model?.contextWindow,desiredMaxOutput:session.model?.maxTokens??0,context:{version:1,sessionId:session.sessionId,phase:"overflow"},execution:execution??executionFacts(session,"overflow"),signal})}function clearManualCompactionState(session){session._compactionAbortController=void 0,session._resolveIdleWaitIfIdle()}async function compactInternal(session,customInstructions){if(await session._abortInternal(),session._reloadInProgress)return{cancelled:!0,aborted:!0};session._compactionAbortController=new AbortController,session._emit({type:"compaction_start",reason:"manual"});try{if(!session.model)throw new Error(formatNoModelSelectedMessage());let auth=await getSummarizationRequestAuth(session,session.model),{pathEntries,expectedRevision,operationId}=captureCompactionCommitBoundary(session,"manual"),settings2=session.settingsManager.getCompactionSettings(),execution=executionFacts(session,"compaction",operationId),preparation=await prepareCompaction3(session,pathEntries,settings2,execution,session._compactionAbortController.signal);if(!preparation)throw pathEntries[pathEntries.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let{summary,firstKeptEntryId,tokensBefore,usage,details}=await runCompactionSummary(session,preparation,auth,customInstructions,session._compactionAbortController.signal,"manual",execution);if(session._compactionAbortController.signal.aborted||session._reloadInProgress)throw new SessionCancelledError("signal");let compactionCommit=commitCompaction(session,{expectedRevision,operationId,summary,firstKeptEntryId,tokensBefore,details,usage});await dispatchCompactionCommitLifecycle(session,"manual",compactionCommit);let sessionContext=session.sessionManager.buildSessionContext();await session._applyContextTransition(sessionContext.messages,"compaction");let estimatedTokensAfter=estimateMessagesTokens(session.agent.state.messages),compactionResult={summary,firstKeptEntryId,tokensBefore,estimatedTokensAfter,usage,details};return clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:compactionResult,aborted:!1,willRetry:!1}),compactionResult}catch(error2){if(error2 instanceof SessionCancelledError||error2 instanceof Error&&error2.name==="AbortError")return clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:!0,willRetry:!1}),{cancelled:!0,aborted:!0};let errorMessage2=`Compaction failed: ${error2 instanceof Error?error2.message:String(error2)}`;throw clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"manual"},cause:error2}),await dispatchCompactionFailedLifecycle(session,{reason:"manual",errorMessage:errorMessage2}),error2}finally{clearManualCompactionState(session)}}async function checkCompaction(session,assistantMessage,skipAbortedCheck=!0,signal){if(signal?.aborted)return!1;let settings2=session.settingsManager.getCompactionSettings();if(skipAbortedCheck&&assistantMessage.stopReason==="aborted")return!1;let contextWindow=session.model?.contextWindow??0,sameModel=session.model!==void 0&&assistantMessage.provider===session.model.provider&&assistantMessage.model===session.model.id,compactionEntry=getLatestCompactionEntry(session.sessionManager.getBranch());if(compactionEntry!==null&&assistantMessage.timestamp<=new Date(compactionEntry.timestamp).getTime())return!1;let overflow=sameModel?await decideOverflow(session,assistantMessage,void 0,signal):{contextOverflow:!1,recoverableLength:!1},{contextOverflow,recoverableLength}=overflow;if(contextOverflow||recoverableLength){let decision2=await decideCompaction(session,{reason:"overflow",contextOverflow,recoverableLength,canContinue:assistantMessage.stopReason!=="stop",signal});if(await dispatchCompactionDecisionLifecycle(session,{reason:"overflow",compact:decision2.compact,willRetry:decision2.retry===!0,...decision2.failureMessage===void 0?{}:{failureMessage:decision2.failureMessage}}),!decision2.compact){if(decision2.failureMessage&&contextOverflow&&session._overflowRecoveryAttempted&&session._overflowTrimStage<OVERFLOW_TRIM_MAX_STAGES){let stage=session._overflowTrimStage,failureMessage=decision2.failureMessage;return session._enqueueCompaction(async()=>{session._autoCompactionAbortController=new AbortController;let autoCompactionSignal=session._autoCompactionAbortController.signal;try{if(autoCompactionSignal.aborted||session._reloadInProgress)return!1;let messages=session.agent.state.messages,base=messages.length>0&&messages[messages.length-1].role==="assistant"?messages.slice(0,-1):messages,trimmed=trimOverflowProjection(base,stage,settings2.keepRecentTokens);if(trimmed.length===0||trimmed===base){let errorMessage2=overflowTrimFailureMessage(stage,failureMessage);return session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2}),!1}return session._overflowTrimStage=stage+1,session._emit({type:"compaction_start",reason:"overflow"}),await session._applyContextTransition(trimmed,"overflow_recovery"),autoCompactionSignal.aborted||session._reloadInProgress?(session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!0,willRetry:!1}),!1):(session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!0}),!0)}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);return session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2}),!1}finally{session._autoCompactionAbortController=void 0,session._resolveIdleWaitIfIdle()}})}if(decision2.failureMessage){let errorMessage2=contextOverflow?overflowTrimFailureMessage(session._overflowTrimStage,decision2.failureMessage):decision2.failureMessage;session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2})}return!1}let willRetry=decision2.retry===!0;return willRetry&&(session._overflowRecoveryAttempted=!0),await session._runAutoCompaction("overflow",willRetry)}let contextTokens,directContextTokens=assistantMessage.usage?calculateContextTokens2(assistantMessage.usage):0;if(assistantMessage.stopReason==="error"||directContextTokens===0){let messages=session.agent.state.messages,estimate=estimateContextTokens2(messages);if(estimate.lastUsageIndex!==null){let usageMsg=messages[estimate.lastUsageIndex];if(compactionEntry&&usageMsg.role==="assistant"&&usageMsg.timestamp<=new Date(compactionEntry.timestamp).getTime())return!1}contextTokens=estimate.tokens}else contextTokens=directContextTokens;let decision=await decideCompaction(session,{reason:"threshold",contextOverflow:!1,recoverableLength:!1,contextUsage:{contextTokens,contextWindow,reserveTokens:settings2.reserveTokens},canContinue:!1,branchEntries:session.sessionManager.getBranch(),keepRecentTokens:settings2.keepRecentTokens,signal});if(await dispatchCompactionDecisionLifecycle(session,{reason:"threshold",compact:decision.compact,willRetry:decision.retry===!0,contextTokens,contextWindow,reserveTokens:settings2.reserveTokens,...decision.failureMessage===void 0?{}:{failureMessage:decision.failureMessage}}),decision.relief!==void 0&&!decision.compact){session.sessionManager.appendCustomEntry(decision.relief.customType,decision.relief.data);let sessionContext=session.sessionManager.buildSessionContext();return await session._applyContextTransition(sessionContext.messages,"compaction"),session._hostLogger?.info("compaction","policy relief applied",{fields:{customType:decision.relief.customType}}),session.agent.hasQueuedMessages()}return decision.compact?session._runAutoCompaction("threshold",decision.retry===!0):!1}async function runAutoCompaction(session,reason,willRetry){return session._reloadInProgress?!1:enqueueCompaction(session,()=>runAutoCompactionInternal(session,reason,willRetry))}async function runAutoCompactionInternal(session,reason,willRetry){session._autoCompactionAbortController=new AbortController;let autoCompactionSignal=session._autoCompactionAbortController.signal;try{try{if(willRetry){let messages=session.agent.state.messages;messages.length>0&&messages[messages.length-1].role==="assistant"&&await session._applyContextTransition(messages.slice(0,-1),"overflow_recovery")}if(autoCompactionSignal.aborted||session._reloadInProgress)return!1}catch(error2){throw session._autoCompactionAbortController=void 0,error2}let settings2=session.settingsManager.getCompactionSettings(),started=!1;try{if(!session.model)return!1;let auth=await getSummarizationRequestAuth(session,session.model),{pathEntries,expectedRevision,operationId}=captureCompactionCommitBoundary(session,reason),execution=executionFacts(session,"compaction",operationId),preparation=await prepareCompaction3(session,pathEntries,settings2,execution,autoCompactionSignal);if(!preparation)return session._emit({type:"compaction_skipped",reason,cause:"nothing_to_compact"}),!1;session._emit({type:"compaction_start",reason}),started=!0;let{summary,firstKeptEntryId,tokensBefore,usage,details}=await runCompactionSummary(session,preparation,auth,void 0,autoCompactionSignal,reason,execution);if(autoCompactionSignal.aborted||session._reloadInProgress)return session._emit({type:"compaction_end",reason,result:void 0,aborted:!0,willRetry:!1}),!1;let compactionCommit=commitCompaction(session,{expectedRevision,operationId,summary,firstKeptEntryId,tokensBefore,details,usage});await dispatchCompactionCommitLifecycle(session,reason,compactionCommit);let sessionContext=session.sessionManager.buildSessionContext();await session._applyContextTransition(sessionContext.messages,"compaction");let estimatedTokensAfter=estimateMessagesTokens(session.agent.state.messages),result={summary,firstKeptEntryId,tokensBefore,estimatedTokensAfter,usage,details};if(session._emit({type:"compaction_end",reason,result,aborted:!1,willRetry}),willRetry){let messages=session.agent.state.messages,lastMsg=messages[messages.length-1];return lastMsg?.role==="assistant"&&(lastMsg.stopReason==="error"||lastMsg.stopReason==="length")&&await session._applyContextTransition(messages.slice(0,-1),"overflow_recovery"),!0}return session.agent.hasQueuedMessages()}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:"compaction failed";if(started){let formattedErrorMessage=reason==="overflow"?`Context overflow recovery failed: ${errorMessage2}`:`Auto-compaction failed: ${errorMessage2}`;session._emit({type:"compaction_end",reason,result:void 0,aborted:!1,willRetry:!1,errorMessage:formattedErrorMessage}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason},cause:error2}),await dispatchCompactionFailedLifecycle(session,{reason,errorMessage:formattedErrorMessage})}return!1}}finally{session._autoCompactionAbortController=void 0,session._resolveIdleWaitIfIdle()}}function summarizationRetryCallbacks(session,source){let attempts=[];return{onRetryScheduled:(attempt2,_maxAttempts,delayMs,errorMessage2)=>{attempts.push({attempt:attempt2,at:Date.now(),ok:!1,failure:errorMessage2,waitedMs:delayMs}),session._emit({type:"summarization_retry_scheduled",attempt:attempt2,maxAttempts:_maxAttempts,delayMs,errorMessage:errorMessage2})},onRetryAttemptStart:()=>{session._emit({type:"summarization_retry_attempt_start",...source})},onRetryFinished:(success,attempt2,finalError)=>{attempts.push(success?{attempt:attempt2+1,at:Date.now(),ok:!0,waitedMs:0}:{attempt:attempt2+1,at:Date.now(),ok:!1,waitedMs:0,...finalError===void 0?{}:{failure:finalError}}),session._emit({type:"summarization_retry_finished",source,attempts})}}}function summarizationRetryPolicy(session,operationId,inputRevision,signal){let settings2=session.settingsManager.getRetrySettings(),runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let execution=executionFacts(session,"retry",operationId?`${operationId}:retry`:void 0,inputRevision);return{...settings2,classify:message=>runtime.classifyRetry(session._retryPolicyName,{message,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution}),decide:({message,retryable,attempt:attempt2,maxAttempts,baseDelayMs})=>runtime.decideRetry(session._retryPolicyName,{retryable,enabled:settings2.enabled,attempt:attempt2,maxAttempts,baseDelayMs,errorMessage:message.errorMessage,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution})}}async function navigateTree(session,targetId,options={}){if(session.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(session._compactionAbortController!==void 0||session._autoCompactionAbortController!==void 0)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");let oldLeafId=session.sessionManager.getLeafId();if(targetId===oldLeafId)return{cancelled:!1};if(options.summarize&&!session.model)throw new Error("No model available for summarization");let targetEntry=session.sessionManager.getEntry(targetId);if(!targetEntry)throw new Error(`Entry ${targetId} not found`);let{entries:entriesToSummarize}=collectEntriesForBranchSummary2(session.sessionManager,oldLeafId,targetId),customInstructions=options.customInstructions,replaceInstructions=options.replaceInstructions,label=options.label;if(session._reloadInProgress)throw new Error("Session reload in progress; tree navigation is unavailable");if(session._branchSummaryAbortController)throw new Error("Branch navigation is already in progress");session._branchSummaryAbortController=new AbortController;let branchSummaryPromise=new Promise(resolve25=>{session._resolveBranchSummaryPromise=resolve25});session._branchSummaryPromise=branchSummaryPromise;try{let summaryText,summaryDetails,summaryUsage;if(options.summarize&&entriesToSummarize.length>0){let model=session.model,auth=await getSummarizationRequestAuth(session,model),branchSummarySettings=session.settingsManager.getBranchSummarySettings(),runtime=session._capabilityRuntime;if(!runtime||!runtime.hasBranchSummaryPolicy(session._branchSummaryPolicyName))throw new Error(`Branch summary policy is not registered: ${session._branchSummaryPolicyName}`);let execution=executionFacts(session,"branch_summary",`branch_summary:${session.sessionId}:${oldLeafId??"root"}:${targetId}`),result=await runtime.summarizeBranch(session._branchSummaryPolicyName,{entries:entriesToSummarize,model:summaryModelFacts(auth.model),invocation:createSummaryModelInvocationV1(session,auth,summarizationRetryPolicy(session,execution.operationId,execution.inputRevision,session._branchSummaryAbortController.signal),summarizationRetryCallbacks(session,{source:"branchSummary"})),signal:session._branchSummaryAbortController.signal,customInstructions,replaceInstructions,reserveTokens:branchSummarySettings.reserveTokens,context:{version:1,sessionId:session.sessionId,phase:"branch_summary"},execution});if(result.aborted)return{cancelled:!0,aborted:!0};if(result.error)throw new Error(result.error);summaryText=result.summary,summaryUsage=result.usage,summaryDetails={readFiles:result.readFiles||[],modifiedFiles:result.modifiedFiles||[]}}if(session._branchSummaryAbortController.signal.aborted||session._reloadInProgress)return{cancelled:!0,aborted:!0};let newLeafId,editorText;targetEntry.type==="message"&&targetEntry.message.role==="user"?(newLeafId=targetEntry.parentId,editorText=contentText(targetEntry.message.content,"")):targetEntry.type==="custom_message"?(newLeafId=targetEntry.parentId,editorText=contentText(targetEntry.content,"")):newLeafId=targetId;let summaryEntry;if(summaryText){let summaryId=session.sessionManager.branchWithSummary(newLeafId,summaryText,summaryDetails,!1,summaryUsage);summaryEntry=session.sessionManager.getEntry(summaryId),label&&session.sessionManager.appendLabelChange(summaryId,label)}else newLeafId===null?session.sessionManager.resetLeaf():session.sessionManager.branch(newLeafId);label&&!summaryText&&session.sessionManager.appendLabelChange(targetId,label);let sessionContext=session.sessionManager.buildSessionContext();return await session._applyContextTransition(sessionContext.messages,"tree"),{editorText,cancelled:!1,summaryEntry}}finally{session._branchSummaryAbortController=void 0,session._resolveIdleWaitIfIdle(),session._resolveBranchSummaryPromise?.(),session._resolveBranchSummaryPromise=void 0,session._branchSummaryPromise===branchSummaryPromise&&(session._branchSummaryPromise=void 0)}}function requireContextStrategy(session){let name=session._contextStrategyName;if(!name)throw new Error("Context strategy is not configured");let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");if(!runtime.hasContextStrategy(name))throw new Error(`Configured context strategy is not registered: ${name}`);return{runtime,name}}function requireIdleContextOperation(session,operation){if(!session.isIdle)throw new Error(`Cannot ${operation} while the session is running`)}function beginContextTransitionFence(session){session._contextEpoch+=1,session._contextTransitionAbortController.abort("context runtime replaced"),session._contextTransitionAbortController=new AbortController}function isContextTransitionCurrent(session,epoch,allowReload){return!session.isDisposed&&epoch===session._contextEpoch&&(allowReload||!session._reloadInProgress)}function assertContextTransitionCurrent(session,epoch,allowReload){if(!session._isContextTransitionCurrent(epoch,allowReload))throw new Error(session.isDisposed?"Session is disposed; context transition was cancelled":session._reloadInProgress?"Session reload in progress; context transition was cancelled":"Context transition was superseded")}function enqueueContextTransition(session,operation,options){let allowReload=options?.allowReload??!1;if(session.isDisposed)return Promise.reject(new Error("Session is disposed; context transition is unavailable"));if(session._reloadInProgress&&!allowReload)return Promise.reject(new Error("Session reload in progress; context transition is unavailable"));let epoch=session._contextEpoch,fenceSignal=session._contextTransitionAbortController.signal,signal=options?.signal?AbortSignal.any([fenceSignal,options.signal]):fenceSignal,queued=(session._activeContextTransition?.catch(()=>{})??Promise.resolve()).then(()=>(session._assertContextTransitionCurrent(epoch,allowReload),operation(epoch,signal)));return session._activeContextTransition=queued,queued.then(()=>{session._activeContextTransition===queued&&(session._activeContextTransition=void 0)},()=>{session._activeContextTransition===queued&&(session._activeContextTransition=void 0)}),queued}function copyContextMessages(value,strategyName,direction){if(!Array.isArray(value)||value.some(message=>typeof message!="object"||message===null||!("role"in message)||typeof message.role!="string"))throw new Error(direction==="result"?`Context strategy must return an AgentMessage array: ${strategyName}`:`Context transition requires an AgentMessage array: ${strategyName}`);try{return structuredClone(value)}catch(error2){throw new Error(direction==="result"?`Context strategy must return structured-cloneable AgentMessage values: ${strategyName}`:`Context transition requires structured-cloneable AgentMessage values: ${strategyName}`,{cause:error2})}}function applyContextTransition(session,messages,reason="session_replace",signal,options){return session._enqueueContextTransition(async(epoch,transitionSignal)=>{let name=session._contextStrategyName,runtime=session._capabilityRuntime;if(name){if(!runtime)throw new Error("Capability runtime is not available");if(!runtime.hasContextStrategy(name))throw new Error(`Configured context strategy is not registered: ${name}`);let replaced=await runtime.replaceContext(name,session._copyContextMessages(messages,name,"input"),{signal:transitionSignal,reason,sessionId:session.sessionId});session._assertContextTransitionCurrent(epoch,options?.allowReload??!1);let committed=session._copyContextMessages(replaced,name,"result");return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=committed,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason,name),committed}return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=messages,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason),messages},{signal,allowReload:options?.allowReload})}function restoreContextTransition(session,snapshot2,reason,options){return session._enqueueContextTransition(async(epoch,signal)=>{let{runtime,name}=session._requireContextStrategy(),restored=await runtime.restoreContext(name,snapshot2,{signal,reason,sessionId:session.sessionId});session._assertContextTransitionCurrent(epoch,options?.allowReload??!1);let committed=session._copyContextMessages(restored,name,"result");return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=committed,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason,name),committed},{allowReload:options?.allowReload})}async function snapshotContext(session){session._requireIdleContextOperation("snapshot context");let{runtime,name}=session._requireContextStrategy();return runtime.snapshotContext(name,session._copyContextMessages(session.agent.state.messages,name,"input"),{reason:"reload",sessionId:session.sessionId})}async function restoreContext(session,snapshot2){return session._requireIdleContextOperation("restore context"),session._restoreContextTransition(snapshot2,"session_replace")}async function replaceContext(session,context){session._requireIdleContextOperation("replace context");let{name}=session._requireContextStrategy();return session._applyContextTransition(session._copyContextMessages(context,name,"input"),"session_replace")}import{basename as basename7,dirname as dirname17}from"node:path";async function extendResourcesFromExtensions(session,reason){dispatchResourcesDiscoverV1Lifecycle(session,{cwd:session._cwd,reason});let contributed=await dispatchResourcesDiscoverV2Lifecycle(session,reason),{skillPaths,promptPaths,themePaths}=contributed;if(skillPaths.length===0&&promptPaths.length===0&&themePaths.length===0)return;let extensionPaths={skillPaths:session.buildExtensionResourcePaths(skillPaths),promptPaths:session.buildExtensionResourcePaths(promptPaths),themePaths:session.buildExtensionResourcePaths(themePaths)};session._resourceLoader.extendResources(extensionPaths),await session._refreshBootstrapSkills(),session._baseSystemPrompt=session._rebuildSystemPrompt(session.getActiveToolNames()),session.agent.state.systemPrompt=session._baseSystemPrompt}function buildExtensionResourcePaths(session,entries){return entries.map(entry=>{let source=session.getExtensionSourceLabel(entry.extensionPath),baseDir=entry.extensionPath.startsWith("<")?void 0:dirname17(entry.extensionPath);return{path:entry.path,metadata:{source,scope:"temporary",origin:"top-level",baseDir}}})}function getExtensionSourceLabel(extensionPath){return extensionPath.startsWith("<")?`extension:${extensionPath.replace(/[<>]/g,"")}`:`extension:${basename7(extensionPath).replace(/\.(ts|js)$/,"")}`}function collectCommandInfos(session){let templates=session.promptTemplates.map(template=>({name:template.name,description:template.description,source:"prompt",sourceInfo:template.sourceInfo})),skills=session._getAvailableSkills().map(skill=>({name:`skill:${skill.name}`,description:skill.description,source:"skill",sourceInfo:skill.sourceInfo}));return[...templates,...skills]}function wireDefaultLoop(session){let previousPrepareNextTurnWithContext=session.agent.prepareNextTurnWithContext??(session.agent.prepareNextTurn?async(_turn,signal)=>await session.agent.prepareNextTurn?.(signal):void 0);session._initialPrepareNextTurn=previousPrepareNextTurnWithContext;let previousTransform=session.agent.transformContext,transformHead=previousTransform?async(messages,signal)=>await previousTransform(messages,signal):void 0;session.agent.beforeToolCall=async({toolCall,args},signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("beforeToolCall")??[],currentArgs=args,replaced=!1;for(let link of chain){let result=await link({toolCallId:toolCall.id,toolName:toolCall.name,args:currentArgs,signal});if(result){if(result.block){let reason=typeof result.reason=="string"&&result.reason.trim()!==""?result.reason:void 0;return await dispatchToolGateBlockedLifecycle(session,toolCall.id,toolCall.name,reason),result}"args"in result&&(currentArgs=result.args,replaced=!0)}}return replaced?{args:currentArgs}:void 0},session.agent.afterToolCall=async({toolCall,args,result,isError},signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("afterToolCall")??[],current=result,override;for(let link of chain){let linkResult=await link({toolCallId:toolCall.id,toolName:toolCall.name,args,result:current,isError,signal});linkResult!==void 0&&(current=linkResult,override=linkResult)}return override},session.agent.transformContext=async(messages,signal)=>{let current=messages;if(transformHead){let transformed=await transformHead(current,signal);transformed!==void 0&&(current=transformed)}let chain=session._capabilityRuntime?.getLoopHookChain("transformContext")??[];for(let link of chain){let transformed=await link(current,signal);transformed!==void 0&&(current=transformed)}return current},session.agent.prepareNextTurnWithContext=async(turn,signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("prepareNextTurn")??[],current=turn;for(let link of chain){let revised=await link(current,signal);revised!==void 0&&(current=revised)}return current};let previousShouldStopAfterTurn=session.agent.shouldStopAfterTurn;session.agent.shouldStopAfterTurn=async(context,signal)=>{if(previousShouldStopAfterTurn&&await previousShouldStopAfterTurn(context,signal))return!0;let chain=session._capabilityRuntime?.getLoopHookChain("shouldStopAfterTurn")??[];for(let link of chain)if(await link(context,signal))return!0;return!1}}function createLoopWiring(session){return{getSessionId:()=>session.sessionId,getRevision:()=>detachedSessionSnapshot(session.sessionManager.getRevision()),getTurnCorrelationId:()=>session._turnCorrelationId,observeError:(error2,source,event)=>{session._observeLifecycleDeliveryError(error2,source,event)},getImageAutoResize:()=>session.settingsManager.getImageAutoResize(),compactBeforeNextAssistantResponse:(context,signal)=>session._compactBeforeNextAssistantResponse(context,signal),getTurnRefresh:()=>({systemPrompt:session._systemPromptOverride??session._baseSystemPrompt,tools:session.agent.state.tools.slice(),model:session.agent.state.model,thinkingLevel:session.agent.state.thinkingLevel}),getInitialPrepareNextTurn:()=>session._initialPrepareNextTurn,getContextStrategyName:()=>session._contextStrategyName}}async function runPromptLoop(session,messages){return session._loopExecutor?session._loopExecutor(session,messages):runDefaultLoop(session,messages)}async function runDefaultLoop(session,messages,drive=postAgentRun){let policyDecisionController=new AbortController,previousPolicyDecisionController=session._policyDecisionAbortController;session._policyDecisionAbortController=policyDecisionController,session._isAgentRunActive=!0,session._currentRunAborted=!1;let turnCorrelationId=`turn:${++session._turnCorrelationCounter}`;session._turnCorrelationId=turnCorrelationId;try{for(await session.agent.prompt(messages);await drive(session);)await session.agent.continue();return session._currentRunAborted?{status:"aborted",reason:session._lastAbortReason??"interrupted"}:{status:"done"}}finally{session._turnCorrelationId===turnCorrelationId&&(session._turnCorrelationId=void 0);try{session._systemPromptOverride=void 0,session._flushPendingBashMessages(),session._flushPendingCustomMessages(),await session._emitAgentSettled()}finally{session._policyDecisionAbortController===policyDecisionController&&(session._policyDecisionAbortController=previousPolicyDecisionController)}}}async function postAgentRun(session){let msg=session._lastAssistantMessage;if(session._lastAssistantMessage=void 0,!msg)return session._pendingRetryDecision=void 0,!1;let pendingDecision=session._pendingRetryDecision;session._pendingRetryDecision=void 0;let policySignal=session._policyDecisionAbortController?.signal;try{if(pendingDecision?!policySignal?.aborted&&await session._prepareRetry(msg,pendingDecision.decision):await session._isRetryableError(msg,void 0,policySignal)&&await session._prepareRetry(msg))return await decideRunLoop(session,{willRetry:!0,willCompact:!1,queuedFollowUp:session.agent.hasQueuedMessages(),hostWillContinue:!0},policySignal)}catch(error2){if(!policySignal?.aborted)throw error2}msg.stopReason==="error"&&session._retryAttempt>0&&(session._emit({type:"auto_retry_end",success:!1,attempt:session._retryAttempt,finalError:msg.errorMessage}),session._retryAttempt=0);try{if(await session._checkCompaction(msg,!0,policySignal))return await decideRunLoop(session,{willRetry:!1,willCompact:!0,queuedFollowUp:session.agent.hasQueuedMessages(),hostWillContinue:!0},policySignal)}catch(error2){if(!policySignal?.aborted)throw error2}let queuedFollowUp=session.agent.hasQueuedMessages();return decideRunLoop(session,{willRetry:!1,willCompact:!1,queuedFollowUp,hostWillContinue:queuedFollowUp},policySignal)}async function decideRunLoop(session,facts,signal){let runtime=session._capabilityRuntime;if(!runtime?.hasRunLoopStrategy(session._runLoopStrategyName))return facts.hostWillContinue;try{let decision=await runtime.decideRunLoop(session._runLoopStrategyName,{...facts,signal});return facts.hostWillContinue&&decision.continueLoop}catch(error2){if(!signal?.aborted)throw error2;return facts.hostWillContinue}}async function emitModelSelect(session,nextModel,previousModel,source){modelsAreEqual(previousModel,nextModel)||await dispatchModelSelectLifecycle(session,{provider:nextModel.provider,id:nextModel.id},source)}async function setModel(session,model,options={}){if(!await session._modelRuntime.checkAuth(model.provider))throw new Error(`No API key for ${model.provider}/${model.id}`);let previousModel=session.model,thinkingLevel=session._getThinkingLevelForModelSwitch(model);session.agent.state.model=model,session.sessionManager.appendModelChange(model.provider,model.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(model.provider,model.id),session._addPersistedDefaultToNonEmptyScope(model)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(model,previousModel,"set")}function addPersistedDefaultToNonEmptyScope(session,model){if(session._scopedModels.length===0||session._scopedModels.some(scoped=>modelsAreEqual(scoped.model,model)))return;session._scopedModels=[...session._scopedModels,{model}];let enabledModels=session.settingsManager.getEnabledModels();if(!enabledModels?.length)return;let modelReference=`${model.provider}/${model.id}`;enabledModels.some(pattern=>pattern.toLowerCase()===modelReference.toLowerCase())||session.settingsManager.setEnabledModels([...enabledModels,modelReference])}async function cycleModel(session,direction="forward",options={}){return session._scopedModels.length>0?session._cycleScopedModel(direction,options):session._cycleAvailableModel(direction,options)}async function cycleScopedModel(session,direction,options){let availableIds=new Set(session._modelRuntime.getAvailableSnapshot().map(model=>`${model.provider}\0${model.id}`)),scopedModels=session._scopedModels.filter(scoped=>availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));if(scopedModels.length<=1)return;let currentModel=session.model,currentIndex=scopedModels.findIndex(sm=>modelsAreEqual(sm.model,currentModel));currentIndex===-1&&(currentIndex=0);let len=scopedModels.length,nextIndex=direction==="forward"?(currentIndex+1)%len:(currentIndex-1+len)%len,next=scopedModels[nextIndex],thinkingLevel=session._getThinkingLevelForModelSwitch(next.model,next.thinkingLevel);return session.agent.state.model=next.model,session.sessionManager.appendModelChange(next.model.provider,next.model.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(next.model.provider,next.model.id),session._addPersistedDefaultToNonEmptyScope(next.model)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(next.model,currentModel,"cycle"),{model:next.model,thinkingLevel:session.thinkingLevel,isScoped:!0}}async function cycleAvailableModel(session,direction,options){let availableModels=session._modelRuntime.getAvailableSnapshot();if(availableModels.length<=1)return;let currentModel=session.model,currentIndex=availableModels.findIndex(m2=>modelsAreEqual(m2,currentModel));currentIndex===-1&&(currentIndex=0);let len=availableModels.length,nextIndex=direction==="forward"?(currentIndex+1)%len:(currentIndex-1+len)%len,nextModel=availableModels[nextIndex],thinkingLevel=session._getThinkingLevelForModelSwitch(nextModel);return session.agent.state.model=nextModel,session.sessionManager.appendModelChange(nextModel.provider,nextModel.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(nextModel.provider,nextModel.id),session._addPersistedDefaultToNonEmptyScope(nextModel)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(nextModel,currentModel,"cycle"),{model:nextModel,thinkingLevel:session.thinkingLevel,isScoped:!1}}function getScopedModels(session){return session._scopedModels}function modelFactsView(model){return{provider:model.provider,id:model.id,contextWindow:model.contextWindow,maxTokens:model.maxTokens,reasoning:model.reasoning}}function setScopedModels(session,scopedModels){session._scopedModels=scopedModels}function getThinkingLevelForModelSwitch(session,targetModel,explicitLevel){if(explicitLevel!==void 0)return explicitLevel;if(targetModel){let perModel=session.settingsManager.getModelThinkingLevel(targetModel.provider,targetModel.id);if(perModel!==void 0)return perModel}return session.settingsManager.getDefaultThinkingLevel()??session.thinkingLevel??DEFAULT_THINKING_LEVEL}import{existsSync as existsSync10,readFileSync as readFileSync9,writeFileSync as writeFileSync7}from"fs";import{basename as basename8,join as join36}from"path";function parseColor(color){let hexMatch=color.match(/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);if(hexMatch)return{r:Number.parseInt(hexMatch[1],16),g:Number.parseInt(hexMatch[2],16),b:Number.parseInt(hexMatch[3],16)};let rgbMatch=color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);if(rgbMatch)return{r:Number.parseInt(rgbMatch[1],10),g:Number.parseInt(rgbMatch[2],10),b:Number.parseInt(rgbMatch[3],10)}}function getLuminance(r,g2,b2){let toLinear=c2=>{let s=c2/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4};return .2126*toLinear(r)+.7152*toLinear(g2)+.0722*toLinear(b2)}function adjustBrightness(color,factor){let parsed=parseColor(color);if(!parsed)return color;let adjust=c2=>Math.min(255,Math.max(0,Math.round(c2*factor)));return`rgb(${adjust(parsed.r)}, ${adjust(parsed.g)}, ${adjust(parsed.b)})`}function deriveExportColors(baseColor){let parsed=parseColor(baseColor);return parsed?getLuminance(parsed.r,parsed.g,parsed.b)>.5?{pageBg:adjustBrightness(baseColor,.96),cardBg:baseColor,infoBg:`rgb(${Math.min(255,parsed.r+10)}, ${Math.min(255,parsed.g+5)}, ${Math.max(0,parsed.b-20)})`}:{pageBg:adjustBrightness(baseColor,.7),cardBg:adjustBrightness(baseColor,.85),infoBg:`rgb(${Math.min(255,parsed.r+20)}, ${Math.min(255,parsed.g+15)}, ${parsed.b})`}:{pageBg:"rgb(24, 24, 30)",cardBg:"rgb(30, 30, 36)",infoBg:"rgb(60, 55, 40)"}}function generateThemeVars(themeName){let colors=getResolvedThemeColors(themeName),lines=[];for(let[key,value]of Object.entries(colors))lines.push(`--${key}: ${value};`);let themeExport=getThemeExportColors(themeName),userMessageBg=colors.userMessageBg||"#343541",derivedColors=deriveExportColors(userMessageBg);return lines.push(`--exportPageBg: ${themeExport.pageBg??derivedColors.pageBg};`),lines.push(`--exportCardBg: ${themeExport.cardBg??derivedColors.cardBg};`),lines.push(`--exportInfoBg: ${themeExport.infoBg??derivedColors.infoBg};`),lines.join(`
|
|
985
|
+
${getProviderLoginHelp()}`}function withoutDeletedHeaders(headers){return headers?Object.fromEntries(Object.entries(headers).filter(entry=>entry[1]!==null)):void 0}function estimateMessagesTokens(messages){let tokens=0;for(let message of messages)tokens+=estimateTokens2(message);return tokens}var OVERFLOW_TRIM_MAX_STAGES=3,OVERFLOW_TRIM_STAGE2_TARGET_TOKENS=1e4,MICROCOMPACT_COOLDOWN_ASSISTANT_RESPONSES=3;function overflowTrimFailureMessage(attempts,failureMessage){return attempts>0?`Context overflow persists after compaction and ${attempts} trim attempts. ${failureMessage}`:failureMessage}function trimOverflowProjection(messages,stage,keepRecentTokens){if(stage>=2){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="user")return i===0?messages:messages.slice(i);for(let i=messages.length-1;i>=0;i--)if(isTurnStartMessage(messages[i]))return i===0?messages:messages.slice(i);return messages}let target=stage===0?keepRecentTokens:OVERFLOW_TRIM_STAGE2_TARGET_TOKENS,turnStarts=[];for(let i=0;i<messages.length;i++)isTurnStartMessage(messages[i])&&turnStarts.push(i);if(turnStarts.length===0)return messages;let suffixTokens=new Array(messages.length+1).fill(0);for(let i=messages.length-1;i>=0;i--)suffixTokens[i]=suffixTokens[i+1]+estimateTokens2(messages[i]);if(suffixTokens[0]<=target)return messages;for(let start of turnStarts)if(suffixTokens[start]<=target)return messages.slice(start);let floorStart=turnStarts[turnStarts.length-1];return floorStart===0?messages:messages.slice(floorStart)}async function getRequiredRequestAuth(session,model){let result;try{result=await session._modelRuntime.getAuth(model)}catch(error2){let cause=error2 instanceof Error?error2.cause:void 0;throw cause instanceof Error&&cause.message==="authHeader requires a resolved API key"?new Error(formatNoApiKeyFoundMessage(model.provider)):error2}if(result&&(result.auth.apiKey||result.auth.headers))return{model:result.auth.baseUrl?{...model,baseUrl:result.auth.baseUrl}:model,apiKey:result.auth.apiKey,headers:withoutDeletedHeaders(result.auth.headers),env:result.env};throw session._modelRuntime.isUsingOAuth(model.provider)?new Error(`Authentication failed for "${model.provider}". Credentials may have expired or network is unavailable. Run '/login ${model.provider}' to re-authenticate.`):new Error(formatNoApiKeyFoundMessage(model.provider))}async function getSummarizationRequestAuth(session,model){if(session.agent.streamFunction===streamSimple)return getRequiredRequestAuth(session,model);try{let result=await session._modelRuntime.getAuth(model);return result?{model:result.auth.baseUrl?{...model,baseUrl:result.auth.baseUrl}:model,apiKey:result.auth.apiKey,headers:withoutDeletedHeaders(result.auth.headers),env:result.env}:{model}}catch{return{model}}}function summaryModelFacts(model){return{id:model.id,contextWindow:model.contextWindow,maxTokens:model.maxTokens,reasoning:model.reasoning}}function createSummaryModelInvocationV1(session,auth,retry,callbacks,options={}){return{invoke:async(input,signal)=>{let maxTokens=input.maxTokens===void 0||auth.model.maxTokens<=0?input.maxTokens:Math.min(input.maxTokens,auth.model.maxTokens),requestOptions={...maxTokens===void 0?{}:{maxTokens},signal,apiKey:auth.apiKey,headers:auth.headers,env:auth.env,cacheRetention:"none",sessionId:options.routingSessionId??uuidv7()};auth.model.reasoning&&input.thinkingLevel&&input.thinkingLevel!=="off"&&(requestOptions.reasoning=input.thinkingLevel);let context={systemPrompt:input.systemPrompt,messages:[{role:"user",content:[{type:"text",text:input.prompt}],timestamp:Date.now()}]},produce=async()=>{let streamFn=session.agent.streamFunction;return streamFn?(await streamFn(auth.model,context,requestOptions)).result():completeSimple(auth.model,context,requestOptions)},response2;try{response2=await retryAssistantCall(produce,retry,requestOptions.signal,callbacks)}catch(error2){return error2 instanceof Error&&error2.name==="AbortError"?{version:1,status:"aborted"}:{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.transportError,message:error2 instanceof Error?error2.message:String(error2)}}}return response2.stopReason==="aborted"?{version:1,status:"aborted"}:response2.stopReason==="error"?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.providerError,message:response2.errorMessage||"Unknown error"}}:response2.stopReason==="length"?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.lengthCap,message:"generation hit the token cap and the summary is incomplete"}}:response2.content.some(block=>block.type==="toolCall")?{version:1,status:"failed",error:{code:SUMMARY_MODEL_INVOCATION_ERROR_CODES.toolCall,message:"attempted to call a tool"}}:{version:1,status:"completed",text:contentText(response2.content),usage:response2.usage}}}}async function compactBeforeNextAssistantResponse(session,context,signal){let model=session.model,settings2=session.settingsManager.getCompactionSettings();if(!model||model.contextWindow<=0)return context;let contextTokens=estimateContextTokens2(context.messages).tokens,decision=await decideCompaction(session,{reason:"threshold",contextOverflow:!1,recoverableLength:!1,contextUsage:{contextTokens,contextWindow:model.contextWindow,reserveTokens:settings2.reserveTokens},canContinue:!1,microcompactEnabled:settings2.microcompactEnabled&&session._microcompactCooldown===0,signal:signal??session._policyDecisionAbortController?.signal});return await dispatchCompactionDecisionLifecycle(session,{reason:"threshold",compact:decision.compact,willRetry:!1,contextTokens,contextWindow:model.contextWindow,reserveTokens:settings2.reserveTokens,...decision.failureMessage===void 0?{}:{failureMessage:decision.failureMessage}}),decision.compact?(await session._runAutoCompaction("threshold",!1),{...context,messages:session.agent.state.messages.slice()}):context}function executionFacts(session,phase,operationId,revision){let inputRevision=detachedSessionSnapshot(revision??session.sessionManager.getRevision());return Object.freeze({version:1,operationId:operationId??`${phase}:${inputRevision.sessionId}:${inputRevision.sequence}:${inputRevision.leafId??"root"}`,sessionId:session.sessionId,inputRevision,phase})}async function runCompactionSummary(session,preparation,auth,customInstructions,signal,reason,execution){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let result=await runtime.summarizeCompaction(session._compactionPolicyName,{preparation,model:summaryModelFacts(auth.model),invocation:createSummaryModelInvocationV1(session,auth,summarizationRetryPolicy(session,execution.operationId,execution.inputRevision,signal),summarizationRetryCallbacks(session,{source:"compaction",reason}),{routingSessionId:session.sessionId}),customInstructions,signal,reason,thinkingLevel:session.thinkingLevel==="off"?"off":"low",sessionId:session.sessionId,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution});return{...result,usage:result.usage}}async function decideCompaction(session,input){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return session._compactionPolicyName===DEFAULT_COMPACTION_POLICY_NAME&&!runtime.hasCompactionPolicy(session._compactionPolicyName)?(session._hostLogger?.warn("compaction","no compaction policy registered; skipping automatic compaction",{fields:{policyName:session._compactionPolicyName,reason:input.reason}}),{compact:!1,retry:!1}):runtime.decideCompaction(session._compactionPolicyName,{enabled:session.settingsManager.getCompactionSettings().enabled,recoveryAttempted:session._overflowRecoveryAttempted,...input,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution:input.execution??executionFacts(session,"compaction"),signal:input.signal})}async function prepareCompaction3(session,pathEntries,settings2,execution,signal){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let preparation=await runtime.prepareCompaction(session._compactionPolicyName,{entries:pathEntries,settings:settings2,context:{version:1,sessionId:session.sessionId,phase:"compaction"},execution:execution??executionFacts(session,"compaction"),signal});if(preparation===void 0)return;let value=preparation;if(!preparation||typeof preparation!="object"||typeof value.firstKeptEntryId!="string"||!Array.isArray(value.messagesToSummarize)||!Array.isArray(value.turnPrefixMessages)||typeof value.isSplitTurn!="boolean"||!Number.isFinite(value.tokensBefore)||typeof value.fileOps!="object"||typeof value.settings!="object")throw new Error(`Compaction policy returned an invalid preparation: ${session._compactionPolicyName}`);return preparation}function captureCompactionCommitBoundary(session,reason){let pathEntries=session.sessionManager.getBranch(),expectedRevision=session.sessionManager.getRevision();return{pathEntries,expectedRevision,operationId:`compaction:${reason}:${expectedRevision.sessionId}:${expectedRevision.sequence}:${expectedRevision.leafId??"root"}`}}function enqueueCompaction(session,operation){let previous=session._compactionQueue,release;session._compactionQueue=new Promise(resolve25=>{release=resolve25});let queued=previous.then(()=>{if(session._reloadInProgress)throw new Error("Session reload in progress; compaction was not started");return operation()}).finally(release);return session._activeCompactionPromise=queued,queued.then(()=>{session._activeCompactionPromise===queued&&(session._activeCompactionPromise=void 0)},()=>{session._activeCompactionPromise===queued&&(session._activeCompactionPromise=void 0)}),queued}function commitCompaction(session,input){let commit=session.sessionManager.commitCompaction({version:1,operationId:input.operationId,expectedRevision:input.expectedRevision,summary:input.summary,firstKeptEntryId:input.firstKeptEntryId,tokensBefore:input.tokensBefore,details:input.details,fromHook:!1,usage:input.usage});if(commit.status==="revision_conflict")throw new Error(`Compaction commit revision conflict: expected ${input.expectedRevision.sequence}/${input.expectedRevision.leafId??"root"}, current ${commit.currentRevision.sequence}/${commit.currentRevision.leafId??"root"}`);let entry=session.sessionManager.getEntry(commit.entryId);if(entry?.type!=="compaction"||entry.operationId!==input.operationId)throw new Error(`Compaction commit entry is unavailable: ${commit.entryId}`);return{entry,status:commit.status,revision:commit.revision}}async function dispatchCompactionCommitLifecycle(session,reason,commit){try{let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let entry=commit.entry,data={version:1,status:commit.status,entryId:entry.id,operationId:entry.operationId??"",revision:commit.revision,reason,summary:entry.summary,firstKeptEntryId:entry.firstKeptEntryId,tokensBefore:entry.tokensBefore,fromHook:entry.fromHook===!0,...entry.usage===void 0?{}:{usage:entry.usage},...entry.details===void 0?{}:{details:entry.details}},delivery=await runtime.dispatchLifecycle({type:SESSION_COMPACTION_COMMIT_EVENT_ID,version:SESSION_COMPACTION_COMMIT_EVENT_VERSION,phase:"committed",data,operationId:entry.operationId,source:"agent-session"});for(let failure2 of delivery.report.failures)session._observeLifecycleDeliveryError(failure2.error,failure2.pluginId,`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}/${failure2.kind}`)}catch(error2){let report=error2.report;if(report?.failures)for(let failure2 of report.failures)session._observeLifecycleDeliveryError(failure2.error,failure2.pluginId,`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}/${failure2.kind}`);else session._observeLifecycleDeliveryError(error2,"<capability-lifecycle>",`${SESSION_COMPACTION_COMMIT_EVENT_ID}@${SESSION_COMPACTION_COMMIT_EVENT_VERSION}`)}}async function decideOverflow(session,message,execution,signal){let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return runtime.decideOverflow(session._overflowPolicyName,{message,contextWindow:session.model?.contextWindow,desiredMaxOutput:session.model?.maxTokens??0,context:{version:1,sessionId:session.sessionId,phase:"overflow"},execution:execution??executionFacts(session,"overflow"),signal})}function clearManualCompactionState(session){session._compactionAbortController=void 0,session._resolveIdleWaitIfIdle()}async function compactInternal(session,customInstructions){if(await session._abortInternal(),session._reloadInProgress)return{cancelled:!0,aborted:!0};session._compactionAbortController=new AbortController,session._emit({type:"compaction_start",reason:"manual"});try{if(!session.model)throw new Error(formatNoModelSelectedMessage());let auth=await getSummarizationRequestAuth(session,session.model),{pathEntries,expectedRevision,operationId}=captureCompactionCommitBoundary(session,"manual"),settings2=session.settingsManager.getCompactionSettings(),execution=executionFacts(session,"compaction",operationId),preparation=await prepareCompaction3(session,pathEntries,settings2,execution,session._compactionAbortController.signal);if(!preparation)throw pathEntries[pathEntries.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let{summary,firstKeptEntryId,tokensBefore,usage,details}=await runCompactionSummary(session,preparation,auth,customInstructions,session._compactionAbortController.signal,"manual",execution);if(session._compactionAbortController.signal.aborted||session._reloadInProgress)throw new SessionCancelledError("signal");let compactionCommit=commitCompaction(session,{expectedRevision,operationId,summary,firstKeptEntryId,tokensBefore,details,usage});await dispatchCompactionCommitLifecycle(session,"manual",compactionCommit);let sessionContext=session.sessionManager.buildSessionContext();await session._applyContextTransition(sessionContext.messages,"compaction");let estimatedTokensAfter=estimateMessagesTokens(session.agent.state.messages),compactionResult={summary,firstKeptEntryId,tokensBefore,estimatedTokensAfter,usage,details};return clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:compactionResult,aborted:!1,willRetry:!1}),compactionResult}catch(error2){if(error2 instanceof SessionCancelledError||error2 instanceof Error&&error2.name==="AbortError")return clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:!0,willRetry:!1}),{cancelled:!0,aborted:!0};let errorMessage2=`Compaction failed: ${error2 instanceof Error?error2.message:String(error2)}`;throw clearManualCompactionState(session),session._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"manual"},cause:error2}),await dispatchCompactionFailedLifecycle(session,{reason:"manual",errorMessage:errorMessage2}),error2}finally{clearManualCompactionState(session)}}async function checkCompaction(session,assistantMessage,skipAbortedCheck=!0,signal){if(signal?.aborted)return!1;let settings2=session.settingsManager.getCompactionSettings();if(skipAbortedCheck&&assistantMessage.stopReason==="aborted")return!1;let contextWindow=session.model?.contextWindow??0,sameModel=session.model!==void 0&&assistantMessage.provider===session.model.provider&&assistantMessage.model===session.model.id,compactionEntry=getLatestCompactionEntry(session.sessionManager.getBranch());if(compactionEntry!==null&&assistantMessage.timestamp<=new Date(compactionEntry.timestamp).getTime())return!1;let overflow=sameModel?await decideOverflow(session,assistantMessage,void 0,signal):{contextOverflow:!1,recoverableLength:!1},{contextOverflow,recoverableLength}=overflow;if(contextOverflow||recoverableLength){let decision2=await decideCompaction(session,{reason:"overflow",contextOverflow,recoverableLength,canContinue:assistantMessage.stopReason!=="stop",signal});if(await dispatchCompactionDecisionLifecycle(session,{reason:"overflow",compact:decision2.compact,willRetry:decision2.retry===!0,...decision2.failureMessage===void 0?{}:{failureMessage:decision2.failureMessage}}),!decision2.compact){if(decision2.failureMessage&&contextOverflow&&session._overflowRecoveryAttempted&&session._overflowTrimStage<OVERFLOW_TRIM_MAX_STAGES){let stage=session._overflowTrimStage,failureMessage=decision2.failureMessage;return session._enqueueCompaction(async()=>{session._autoCompactionAbortController=new AbortController;let autoCompactionSignal=session._autoCompactionAbortController.signal;try{if(autoCompactionSignal.aborted||session._reloadInProgress)return!1;let messages=session.agent.state.messages,base=messages.length>0&&messages[messages.length-1].role==="assistant"?messages.slice(0,-1):messages,trimmed=trimOverflowProjection(base,stage,settings2.keepRecentTokens);if(trimmed.length===0||trimmed===base){let errorMessage2=overflowTrimFailureMessage(stage,failureMessage);return session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2}),!1}return session._overflowTrimStage=stage+1,session._emit({type:"compaction_start",reason:"overflow"}),await session._applyContextTransition(trimmed,"overflow_recovery"),autoCompactionSignal.aborted||session._reloadInProgress?(session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!0,willRetry:!1}),!1):(session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!0}),!0)}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);return session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2}),!1}finally{session._autoCompactionAbortController=void 0,session._resolveIdleWaitIfIdle()}})}if(decision2.failureMessage){let errorMessage2=contextOverflow?overflowTrimFailureMessage(session._overflowTrimStage,decision2.failureMessage):decision2.failureMessage;session._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:errorMessage2}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason:"overflow"},cause:errorMessage2}),await dispatchCompactionFailedLifecycle(session,{reason:"overflow",errorMessage:errorMessage2})}return!1}let willRetry=decision2.retry===!0;return willRetry&&(session._overflowRecoveryAttempted=!0),await session._runAutoCompaction("overflow",willRetry)}let contextTokens,directContextTokens=assistantMessage.usage?calculateContextTokens2(assistantMessage.usage):0;if(assistantMessage.stopReason==="error"||directContextTokens===0){let messages=session.agent.state.messages,estimate=estimateContextTokens2(messages);if(estimate.lastUsageIndex!==null){let usageMsg=messages[estimate.lastUsageIndex];if(compactionEntry&&usageMsg.role==="assistant"&&usageMsg.timestamp<=new Date(compactionEntry.timestamp).getTime())return!1}contextTokens=estimate.tokens}else contextTokens=directContextTokens;let decision=await decideCompaction(session,{reason:"threshold",contextOverflow:!1,recoverableLength:!1,contextUsage:{contextTokens,contextWindow,reserveTokens:settings2.reserveTokens},canContinue:!1,branchEntries:session.sessionManager.getBranch(),keepRecentTokens:settings2.keepRecentTokens,microcompactEnabled:settings2.microcompactEnabled&&session._microcompactCooldown===0,signal});if(await dispatchCompactionDecisionLifecycle(session,{reason:"threshold",compact:decision.compact,willRetry:decision.retry===!0,contextTokens,contextWindow,reserveTokens:settings2.reserveTokens,...decision.failureMessage===void 0?{}:{failureMessage:decision.failureMessage}}),decision.relief!==void 0&&!decision.compact){session.sessionManager.appendCustomEntry(decision.relief.customType,decision.relief.data);let sessionContext=session.sessionManager.buildSessionContext();return await session._applyContextTransition(sessionContext.messages,"compaction"),session._microcompactCooldown=MICROCOMPACT_COOLDOWN_ASSISTANT_RESPONSES,session._hostLogger?.info("compaction","policy relief applied",{fields:{customType:decision.relief.customType}}),session.agent.hasQueuedMessages()}return decision.compact?session._runAutoCompaction("threshold",decision.retry===!0):!1}async function runAutoCompaction(session,reason,willRetry){return session._reloadInProgress?!1:enqueueCompaction(session,()=>runAutoCompactionInternal(session,reason,willRetry))}async function runAutoCompactionInternal(session,reason,willRetry){session._autoCompactionAbortController=new AbortController;let autoCompactionSignal=session._autoCompactionAbortController.signal;try{try{if(willRetry){let messages=session.agent.state.messages;messages.length>0&&messages[messages.length-1].role==="assistant"&&await session._applyContextTransition(messages.slice(0,-1),"overflow_recovery")}if(autoCompactionSignal.aborted||session._reloadInProgress)return!1}catch(error2){throw session._autoCompactionAbortController=void 0,error2}let settings2=session.settingsManager.getCompactionSettings(),started=!1;try{if(!session.model)return!1;let auth=await getSummarizationRequestAuth(session,session.model),{pathEntries,expectedRevision,operationId}=captureCompactionCommitBoundary(session,reason),execution=executionFacts(session,"compaction",operationId),preparation=await prepareCompaction3(session,pathEntries,settings2,execution,autoCompactionSignal);if(!preparation)return session._emit({type:"compaction_skipped",reason,cause:"nothing_to_compact"}),!1;session._emit({type:"compaction_start",reason}),started=!0;let{summary,firstKeptEntryId,tokensBefore,usage,details}=await runCompactionSummary(session,preparation,auth,void 0,autoCompactionSignal,reason,execution);if(autoCompactionSignal.aborted||session._reloadInProgress)return session._emit({type:"compaction_end",reason,result:void 0,aborted:!0,willRetry:!1}),!1;let compactionCommit=commitCompaction(session,{expectedRevision,operationId,summary,firstKeptEntryId,tokensBefore,details,usage});await dispatchCompactionCommitLifecycle(session,reason,compactionCommit);let sessionContext=session.sessionManager.buildSessionContext();await session._applyContextTransition(sessionContext.messages,"compaction");let estimatedTokensAfter=estimateMessagesTokens(session.agent.state.messages),result={summary,firstKeptEntryId,tokensBefore,estimatedTokensAfter,usage,details};if(session._emit({type:"compaction_end",reason,result,aborted:!1,willRetry}),willRetry){let messages=session.agent.state.messages,lastMsg=messages[messages.length-1];return lastMsg?.role==="assistant"&&(lastMsg.stopReason==="error"||lastMsg.stopReason==="length")&&await session._applyContextTransition(messages.slice(0,-1),"overflow_recovery"),!0}return session.agent.hasQueuedMessages()}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:"compaction failed";if(started){let formattedErrorMessage=reason==="overflow"?`Context overflow recovery failed: ${errorMessage2}`:`Auto-compaction failed: ${errorMessage2}`;session._emit({type:"compaction_end",reason,result:void 0,aborted:!1,willRetry:!1,errorMessage:formattedErrorMessage}),session._hostLogger?.error("compaction","compaction failed",{fields:{reason},cause:error2}),await dispatchCompactionFailedLifecycle(session,{reason,errorMessage:formattedErrorMessage})}return!1}}finally{session._autoCompactionAbortController=void 0,session._resolveIdleWaitIfIdle()}}function summarizationRetryCallbacks(session,source){let attempts=[];return{onRetryScheduled:(attempt2,_maxAttempts,delayMs,errorMessage2)=>{attempts.push({attempt:attempt2,at:Date.now(),ok:!1,failure:errorMessage2,waitedMs:delayMs}),session._emit({type:"summarization_retry_scheduled",attempt:attempt2,maxAttempts:_maxAttempts,delayMs,errorMessage:errorMessage2})},onRetryAttemptStart:()=>{session._emit({type:"summarization_retry_attempt_start",...source})},onRetryFinished:(success,attempt2,finalError)=>{attempts.push(success?{attempt:attempt2+1,at:Date.now(),ok:!0,waitedMs:0}:{attempt:attempt2+1,at:Date.now(),ok:!1,waitedMs:0,...finalError===void 0?{}:{failure:finalError}}),session._emit({type:"summarization_retry_finished",source,attempts})}}}function summarizationRetryPolicy(session,operationId,inputRevision,signal){let settings2=session.settingsManager.getRetrySettings(),runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let execution=executionFacts(session,"retry",operationId?`${operationId}:retry`:void 0,inputRevision);return{...settings2,classify:message=>runtime.classifyRetry(session._retryPolicyName,{message,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution}),decide:({message,retryable,attempt:attempt2,maxAttempts,baseDelayMs})=>runtime.decideRetry(session._retryPolicyName,{retryable,enabled:settings2.enabled,attempt:attempt2,maxAttempts,baseDelayMs,errorMessage:message.errorMessage,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution})}}async function navigateTree(session,targetId,options={}){if(session.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(session._compactionAbortController!==void 0||session._autoCompactionAbortController!==void 0)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");let oldLeafId=session.sessionManager.getLeafId();if(targetId===oldLeafId)return{cancelled:!1};if(options.summarize&&!session.model)throw new Error("No model available for summarization");let targetEntry=session.sessionManager.getEntry(targetId);if(!targetEntry)throw new Error(`Entry ${targetId} not found`);let{entries:entriesToSummarize}=collectEntriesForBranchSummary2(session.sessionManager,oldLeafId,targetId),customInstructions=options.customInstructions,replaceInstructions=options.replaceInstructions,label=options.label;if(session._reloadInProgress)throw new Error("Session reload in progress; tree navigation is unavailable");if(session._branchSummaryAbortController)throw new Error("Branch navigation is already in progress");session._branchSummaryAbortController=new AbortController;let branchSummaryPromise=new Promise(resolve25=>{session._resolveBranchSummaryPromise=resolve25});session._branchSummaryPromise=branchSummaryPromise;try{let summaryText,summaryDetails,summaryUsage;if(options.summarize&&entriesToSummarize.length>0){let model=session.model,auth=await getSummarizationRequestAuth(session,model),branchSummarySettings=session.settingsManager.getBranchSummarySettings(),runtime=session._capabilityRuntime;if(!runtime||!runtime.hasBranchSummaryPolicy(session._branchSummaryPolicyName))throw new Error(`Branch summary policy is not registered: ${session._branchSummaryPolicyName}`);let execution=executionFacts(session,"branch_summary",`branch_summary:${session.sessionId}:${oldLeafId??"root"}:${targetId}`),result=await runtime.summarizeBranch(session._branchSummaryPolicyName,{entries:entriesToSummarize,model:summaryModelFacts(auth.model),invocation:createSummaryModelInvocationV1(session,auth,summarizationRetryPolicy(session,execution.operationId,execution.inputRevision,session._branchSummaryAbortController.signal),summarizationRetryCallbacks(session,{source:"branchSummary"})),signal:session._branchSummaryAbortController.signal,customInstructions,replaceInstructions,reserveTokens:branchSummarySettings.reserveTokens,context:{version:1,sessionId:session.sessionId,phase:"branch_summary"},execution});if(result.aborted)return{cancelled:!0,aborted:!0};if(result.error)throw new Error(result.error);summaryText=result.summary,summaryUsage=result.usage,summaryDetails={readFiles:result.readFiles||[],modifiedFiles:result.modifiedFiles||[]}}if(session._branchSummaryAbortController.signal.aborted||session._reloadInProgress)return{cancelled:!0,aborted:!0};let newLeafId,editorText;targetEntry.type==="message"&&targetEntry.message.role==="user"?(newLeafId=targetEntry.parentId,editorText=contentText(targetEntry.message.content,"")):targetEntry.type==="custom_message"?(newLeafId=targetEntry.parentId,editorText=contentText(targetEntry.content,"")):newLeafId=targetId;let summaryEntry;if(summaryText){let summaryId=session.sessionManager.branchWithSummary(newLeafId,summaryText,summaryDetails,!1,summaryUsage);summaryEntry=session.sessionManager.getEntry(summaryId),label&&session.sessionManager.appendLabelChange(summaryId,label)}else newLeafId===null?session.sessionManager.resetLeaf():session.sessionManager.branch(newLeafId);label&&!summaryText&&session.sessionManager.appendLabelChange(targetId,label);let sessionContext=session.sessionManager.buildSessionContext();return await session._applyContextTransition(sessionContext.messages,"tree"),{editorText,cancelled:!1,summaryEntry}}finally{session._branchSummaryAbortController=void 0,session._resolveIdleWaitIfIdle(),session._resolveBranchSummaryPromise?.(),session._resolveBranchSummaryPromise=void 0,session._branchSummaryPromise===branchSummaryPromise&&(session._branchSummaryPromise=void 0)}}function requireContextStrategy(session){let name=session._contextStrategyName;if(!name)throw new Error("Context strategy is not configured");let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");if(!runtime.hasContextStrategy(name))throw new Error(`Configured context strategy is not registered: ${name}`);return{runtime,name}}function requireIdleContextOperation(session,operation){if(!session.isIdle)throw new Error(`Cannot ${operation} while the session is running`)}function beginContextTransitionFence(session){session._contextEpoch+=1,session._contextTransitionAbortController.abort("context runtime replaced"),session._contextTransitionAbortController=new AbortController}function isContextTransitionCurrent(session,epoch,allowReload){return!session.isDisposed&&epoch===session._contextEpoch&&(allowReload||!session._reloadInProgress)}function assertContextTransitionCurrent(session,epoch,allowReload){if(!session._isContextTransitionCurrent(epoch,allowReload))throw new Error(session.isDisposed?"Session is disposed; context transition was cancelled":session._reloadInProgress?"Session reload in progress; context transition was cancelled":"Context transition was superseded")}function enqueueContextTransition(session,operation,options){let allowReload=options?.allowReload??!1;if(session.isDisposed)return Promise.reject(new Error("Session is disposed; context transition is unavailable"));if(session._reloadInProgress&&!allowReload)return Promise.reject(new Error("Session reload in progress; context transition is unavailable"));let epoch=session._contextEpoch,fenceSignal=session._contextTransitionAbortController.signal,signal=options?.signal?AbortSignal.any([fenceSignal,options.signal]):fenceSignal,queued=(session._activeContextTransition?.catch(()=>{})??Promise.resolve()).then(()=>(session._assertContextTransitionCurrent(epoch,allowReload),operation(epoch,signal)));return session._activeContextTransition=queued,queued.then(()=>{session._activeContextTransition===queued&&(session._activeContextTransition=void 0)},()=>{session._activeContextTransition===queued&&(session._activeContextTransition=void 0)}),queued}function copyContextMessages(value,strategyName,direction){if(!Array.isArray(value)||value.some(message=>typeof message!="object"||message===null||!("role"in message)||typeof message.role!="string"))throw new Error(direction==="result"?`Context strategy must return an AgentMessage array: ${strategyName}`:`Context transition requires an AgentMessage array: ${strategyName}`);try{return structuredClone(value)}catch(error2){throw new Error(direction==="result"?`Context strategy must return structured-cloneable AgentMessage values: ${strategyName}`:`Context transition requires structured-cloneable AgentMessage values: ${strategyName}`,{cause:error2})}}function applyContextTransition(session,messages,reason="session_replace",signal,options){return session._enqueueContextTransition(async(epoch,transitionSignal)=>{let name=session._contextStrategyName,runtime=session._capabilityRuntime;if(name){if(!runtime)throw new Error("Capability runtime is not available");if(!runtime.hasContextStrategy(name))throw new Error(`Configured context strategy is not registered: ${name}`);let replaced=await runtime.replaceContext(name,session._copyContextMessages(messages,name,"input"),{signal:transitionSignal,reason,sessionId:session.sessionId});session._assertContextTransitionCurrent(epoch,options?.allowReload??!1);let committed=session._copyContextMessages(replaced,name,"result");return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=committed,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason,name),committed}return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=messages,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason),messages},{signal,allowReload:options?.allowReload})}function restoreContextTransition(session,snapshot2,reason,options){return session._enqueueContextTransition(async(epoch,signal)=>{let{runtime,name}=session._requireContextStrategy(),restored=await runtime.restoreContext(name,snapshot2,{signal,reason,sessionId:session.sessionId});session._assertContextTransitionCurrent(epoch,options?.allowReload??!1);let committed=session._copyContextMessages(restored,name,"result");return session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),session.agent.state.messages=committed,session._contextRevision+=1,session._assertContextTransitionCurrent(epoch,options?.allowReload??!1),await session._dispatchContextReplacedLifecycle(reason,name),committed},{allowReload:options?.allowReload})}async function snapshotContext(session){session._requireIdleContextOperation("snapshot context");let{runtime,name}=session._requireContextStrategy();return runtime.snapshotContext(name,session._copyContextMessages(session.agent.state.messages,name,"input"),{reason:"reload",sessionId:session.sessionId})}async function restoreContext(session,snapshot2){return session._requireIdleContextOperation("restore context"),session._restoreContextTransition(snapshot2,"session_replace")}async function replaceContext(session,context){session._requireIdleContextOperation("replace context");let{name}=session._requireContextStrategy();return session._applyContextTransition(session._copyContextMessages(context,name,"input"),"session_replace")}import{basename as basename7,dirname as dirname17}from"node:path";async function extendResourcesFromExtensions(session,reason){dispatchResourcesDiscoverV1Lifecycle(session,{cwd:session._cwd,reason});let contributed=await dispatchResourcesDiscoverV2Lifecycle(session,reason),{skillPaths,promptPaths,themePaths}=contributed;if(skillPaths.length===0&&promptPaths.length===0&&themePaths.length===0)return;let extensionPaths={skillPaths:session.buildExtensionResourcePaths(skillPaths),promptPaths:session.buildExtensionResourcePaths(promptPaths),themePaths:session.buildExtensionResourcePaths(themePaths)};session._resourceLoader.extendResources(extensionPaths),await session._refreshBootstrapSkills(),session._baseSystemPrompt=session._rebuildSystemPrompt(session.getActiveToolNames()),session.agent.state.systemPrompt=session._baseSystemPrompt}function buildExtensionResourcePaths(session,entries){return entries.map(entry=>{let source=session.getExtensionSourceLabel(entry.extensionPath),baseDir=entry.extensionPath.startsWith("<")?void 0:dirname17(entry.extensionPath);return{path:entry.path,metadata:{source,scope:"temporary",origin:"top-level",baseDir}}})}function getExtensionSourceLabel(extensionPath){return extensionPath.startsWith("<")?`extension:${extensionPath.replace(/[<>]/g,"")}`:`extension:${basename7(extensionPath).replace(/\.(ts|js)$/,"")}`}function collectCommandInfos(session){let templates=session.promptTemplates.map(template=>({name:template.name,description:template.description,source:"prompt",sourceInfo:template.sourceInfo})),skills=session._getAvailableSkills().map(skill=>({name:`skill:${skill.name}`,description:skill.description,source:"skill",sourceInfo:skill.sourceInfo}));return[...templates,...skills]}function wireDefaultLoop(session){let previousPrepareNextTurnWithContext=session.agent.prepareNextTurnWithContext??(session.agent.prepareNextTurn?async(_turn,signal)=>await session.agent.prepareNextTurn?.(signal):void 0);session._initialPrepareNextTurn=previousPrepareNextTurnWithContext;let previousTransform=session.agent.transformContext,transformHead=previousTransform?async(messages,signal)=>await previousTransform(messages,signal):void 0;session.agent.beforeToolCall=async({toolCall,args},signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("beforeToolCall")??[],currentArgs=args,replaced=!1;for(let link of chain){let result=await link({toolCallId:toolCall.id,toolName:toolCall.name,args:currentArgs,signal});if(result){if(result.block){let reason=typeof result.reason=="string"&&result.reason.trim()!==""?result.reason:void 0;return await dispatchToolGateBlockedLifecycle(session,toolCall.id,toolCall.name,reason),result}"args"in result&&(currentArgs=result.args,replaced=!0)}}return replaced?{args:currentArgs}:void 0},session.agent.afterToolCall=async({toolCall,args,result,isError},signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("afterToolCall")??[],current=result,override;for(let link of chain){let linkResult=await link({toolCallId:toolCall.id,toolName:toolCall.name,args,result:current,isError,signal});linkResult!==void 0&&(current=linkResult,override=linkResult)}return override},session.agent.transformContext=async(messages,signal)=>{let current=messages;if(transformHead){let transformed=await transformHead(current,signal);transformed!==void 0&&(current=transformed)}let chain=session._capabilityRuntime?.getLoopHookChain("transformContext")??[];for(let link of chain){let transformed=await link(current,signal);transformed!==void 0&&(current=transformed)}return current},session.agent.prepareNextTurnWithContext=async(turn,signal)=>{let chain=session._capabilityRuntime?.getLoopHookChain("prepareNextTurn")??[],current=turn;for(let link of chain){let revised=await link(current,signal);revised!==void 0&&(current=revised)}return current};let previousShouldStopAfterTurn=session.agent.shouldStopAfterTurn;session.agent.shouldStopAfterTurn=async(context,signal)=>{if(previousShouldStopAfterTurn&&await previousShouldStopAfterTurn(context,signal))return!0;let chain=session._capabilityRuntime?.getLoopHookChain("shouldStopAfterTurn")??[];for(let link of chain)if(await link(context,signal))return!0;return!1}}function createLoopWiring(session){return{getSessionId:()=>session.sessionId,getRevision:()=>detachedSessionSnapshot(session.sessionManager.getRevision()),getTurnCorrelationId:()=>session._turnCorrelationId,observeError:(error2,source,event)=>{session._observeLifecycleDeliveryError(error2,source,event)},getImageAutoResize:()=>session.settingsManager.getImageAutoResize(),compactBeforeNextAssistantResponse:(context,signal)=>session._compactBeforeNextAssistantResponse(context,signal),getTurnRefresh:()=>({systemPrompt:session._systemPromptOverride??session._baseSystemPrompt,tools:session.agent.state.tools.slice(),model:session.agent.state.model,thinkingLevel:session.agent.state.thinkingLevel}),getInitialPrepareNextTurn:()=>session._initialPrepareNextTurn,getContextStrategyName:()=>session._contextStrategyName}}async function runPromptLoop(session,messages){return session._loopExecutor?session._loopExecutor(session,messages):runDefaultLoop(session,messages)}async function runDefaultLoop(session,messages,drive=postAgentRun){let policyDecisionController=new AbortController,previousPolicyDecisionController=session._policyDecisionAbortController;session._policyDecisionAbortController=policyDecisionController,session._isAgentRunActive=!0,session._currentRunAborted=!1;let turnCorrelationId=`turn:${++session._turnCorrelationCounter}`;session._turnCorrelationId=turnCorrelationId;try{for(await session.agent.prompt(messages);await drive(session);)await session.agent.continue();return session._currentRunAborted?{status:"aborted",reason:session._lastAbortReason??"interrupted"}:{status:"done"}}finally{session._turnCorrelationId===turnCorrelationId&&(session._turnCorrelationId=void 0);try{session._systemPromptOverride=void 0,session._flushPendingBashMessages(),session._flushPendingCustomMessages(),await session._emitAgentSettled()}finally{session._policyDecisionAbortController===policyDecisionController&&(session._policyDecisionAbortController=previousPolicyDecisionController)}}}async function postAgentRun(session){let msg=session._lastAssistantMessage;if(session._lastAssistantMessage=void 0,!msg)return session._pendingRetryDecision=void 0,!1;let pendingDecision=session._pendingRetryDecision;session._pendingRetryDecision=void 0;let policySignal=session._policyDecisionAbortController?.signal;try{if(pendingDecision?!policySignal?.aborted&&await session._prepareRetry(msg,pendingDecision.decision):await session._isRetryableError(msg,void 0,policySignal)&&await session._prepareRetry(msg))return await decideRunLoop(session,{willRetry:!0,willCompact:!1,queuedFollowUp:session.agent.hasQueuedMessages(),hostWillContinue:!0},policySignal)}catch(error2){if(!policySignal?.aborted)throw error2}msg.stopReason==="error"&&session._retryAttempt>0&&(session._emit({type:"auto_retry_end",success:!1,attempt:session._retryAttempt,finalError:msg.errorMessage}),session._retryAttempt=0);try{if(await session._checkCompaction(msg,!0,policySignal))return await decideRunLoop(session,{willRetry:!1,willCompact:!0,queuedFollowUp:session.agent.hasQueuedMessages(),hostWillContinue:!0},policySignal)}catch(error2){if(!policySignal?.aborted)throw error2}let queuedFollowUp=session.agent.hasQueuedMessages();return decideRunLoop(session,{willRetry:!1,willCompact:!1,queuedFollowUp,hostWillContinue:queuedFollowUp},policySignal)}async function decideRunLoop(session,facts,signal){let runtime=session._capabilityRuntime;if(!runtime?.hasRunLoopStrategy(session._runLoopStrategyName))return facts.hostWillContinue;try{let decision=await runtime.decideRunLoop(session._runLoopStrategyName,{...facts,signal});return facts.hostWillContinue&&decision.continueLoop}catch(error2){if(!signal?.aborted)throw error2;return facts.hostWillContinue}}async function emitModelSelect(session,nextModel,previousModel,source){modelsAreEqual(previousModel,nextModel)||await dispatchModelSelectLifecycle(session,{provider:nextModel.provider,id:nextModel.id},source)}async function setModel(session,model,options={}){if(!await session._modelRuntime.checkAuth(model.provider))throw new Error(`No API key for ${model.provider}/${model.id}`);let previousModel=session.model,thinkingLevel=session._getThinkingLevelForModelSwitch(model);session.agent.state.model=model,session.sessionManager.appendModelChange(model.provider,model.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(model.provider,model.id),session._addPersistedDefaultToNonEmptyScope(model)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(model,previousModel,"set")}function addPersistedDefaultToNonEmptyScope(session,model){if(session._scopedModels.length===0||session._scopedModels.some(scoped=>modelsAreEqual(scoped.model,model)))return;session._scopedModels=[...session._scopedModels,{model}];let enabledModels=session.settingsManager.getEnabledModels();if(!enabledModels?.length)return;let modelReference=`${model.provider}/${model.id}`;enabledModels.some(pattern=>pattern.toLowerCase()===modelReference.toLowerCase())||session.settingsManager.setEnabledModels([...enabledModels,modelReference])}async function cycleModel(session,direction="forward",options={}){return session._scopedModels.length>0?session._cycleScopedModel(direction,options):session._cycleAvailableModel(direction,options)}async function cycleScopedModel(session,direction,options){let availableIds=new Set(session._modelRuntime.getAvailableSnapshot().map(model=>`${model.provider}\0${model.id}`)),scopedModels=session._scopedModels.filter(scoped=>availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));if(scopedModels.length<=1)return;let currentModel=session.model,currentIndex=scopedModels.findIndex(sm=>modelsAreEqual(sm.model,currentModel));currentIndex===-1&&(currentIndex=0);let len=scopedModels.length,nextIndex=direction==="forward"?(currentIndex+1)%len:(currentIndex-1+len)%len,next=scopedModels[nextIndex],thinkingLevel=session._getThinkingLevelForModelSwitch(next.model,next.thinkingLevel);return session.agent.state.model=next.model,session.sessionManager.appendModelChange(next.model.provider,next.model.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(next.model.provider,next.model.id),session._addPersistedDefaultToNonEmptyScope(next.model)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(next.model,currentModel,"cycle"),{model:next.model,thinkingLevel:session.thinkingLevel,isScoped:!0}}async function cycleAvailableModel(session,direction,options){let availableModels=session._modelRuntime.getAvailableSnapshot();if(availableModels.length<=1)return;let currentModel=session.model,currentIndex=availableModels.findIndex(m2=>modelsAreEqual(m2,currentModel));currentIndex===-1&&(currentIndex=0);let len=availableModels.length,nextIndex=direction==="forward"?(currentIndex+1)%len:(currentIndex-1+len)%len,nextModel=availableModels[nextIndex],thinkingLevel=session._getThinkingLevelForModelSwitch(nextModel);return session.agent.state.model=nextModel,session.sessionManager.appendModelChange(nextModel.provider,nextModel.id),options.persist&&(session.settingsManager.setDefaultModelAndProvider(nextModel.provider,nextModel.id),session._addPersistedDefaultToNonEmptyScope(nextModel)),session.setThinkingLevel(thinkingLevel),await session._emitModelSelect(nextModel,currentModel,"cycle"),{model:nextModel,thinkingLevel:session.thinkingLevel,isScoped:!1}}function getScopedModels(session){return session._scopedModels}function modelFactsView(model){return{provider:model.provider,id:model.id,contextWindow:model.contextWindow,maxTokens:model.maxTokens,reasoning:model.reasoning}}function setScopedModels(session,scopedModels){session._scopedModels=scopedModels}function getThinkingLevelForModelSwitch(session,targetModel,explicitLevel){if(explicitLevel!==void 0)return explicitLevel;if(targetModel){let perModel=session.settingsManager.getModelThinkingLevel(targetModel.provider,targetModel.id);if(perModel!==void 0)return perModel}return session.settingsManager.getDefaultThinkingLevel()??session.thinkingLevel??DEFAULT_THINKING_LEVEL}import{existsSync as existsSync10,readFileSync as readFileSync9,writeFileSync as writeFileSync7}from"fs";import{basename as basename8,join as join36}from"path";function parseColor(color){let hexMatch=color.match(/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);if(hexMatch)return{r:Number.parseInt(hexMatch[1],16),g:Number.parseInt(hexMatch[2],16),b:Number.parseInt(hexMatch[3],16)};let rgbMatch=color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);if(rgbMatch)return{r:Number.parseInt(rgbMatch[1],10),g:Number.parseInt(rgbMatch[2],10),b:Number.parseInt(rgbMatch[3],10)}}function getLuminance(r,g2,b2){let toLinear=c2=>{let s=c2/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4};return .2126*toLinear(r)+.7152*toLinear(g2)+.0722*toLinear(b2)}function adjustBrightness(color,factor){let parsed=parseColor(color);if(!parsed)return color;let adjust=c2=>Math.min(255,Math.max(0,Math.round(c2*factor)));return`rgb(${adjust(parsed.r)}, ${adjust(parsed.g)}, ${adjust(parsed.b)})`}function deriveExportColors(baseColor){let parsed=parseColor(baseColor);return parsed?getLuminance(parsed.r,parsed.g,parsed.b)>.5?{pageBg:adjustBrightness(baseColor,.96),cardBg:baseColor,infoBg:`rgb(${Math.min(255,parsed.r+10)}, ${Math.min(255,parsed.g+5)}, ${Math.max(0,parsed.b-20)})`}:{pageBg:adjustBrightness(baseColor,.7),cardBg:adjustBrightness(baseColor,.85),infoBg:`rgb(${Math.min(255,parsed.r+20)}, ${Math.min(255,parsed.g+15)}, ${parsed.b})`}:{pageBg:"rgb(24, 24, 30)",cardBg:"rgb(30, 30, 36)",infoBg:"rgb(60, 55, 40)"}}function generateThemeVars(themeName){let colors=getResolvedThemeColors(themeName),lines=[];for(let[key,value]of Object.entries(colors))lines.push(`--${key}: ${value};`);let themeExport=getThemeExportColors(themeName),userMessageBg=colors.userMessageBg||"#343541",derivedColors=deriveExportColors(userMessageBg);return lines.push(`--exportPageBg: ${themeExport.pageBg??derivedColors.pageBg};`),lines.push(`--exportCardBg: ${themeExport.cardBg??derivedColors.cardBg};`),lines.push(`--exportInfoBg: ${themeExport.infoBg??derivedColors.infoBg};`),lines.join(`
|
|
986
986
|
`)}function generateHtml(sessionData,themeName){let templateDir=getExportTemplateDir(),template=readFileSync9(join36(templateDir,"template.html"),"utf-8"),templateCss=readFileSync9(join36(templateDir,"template.css"),"utf-8"),templateJs=readFileSync9(join36(templateDir,"template.js"),"utf-8"),markedJs=readFileSync9(join36(templateDir,"vendor","marked.min.js"),"utf-8"),hljsJs=readFileSync9(join36(templateDir,"vendor","highlight.min.js"),"utf-8"),themeVars=generateThemeVars(themeName),colors=getResolvedThemeColors(themeName),themeExport=getThemeExportColors(themeName),derivedExportColors=deriveExportColors(colors.userMessageBg||"#343541"),bodyBg=themeExport.pageBg??derivedExportColors.pageBg,containerBg=themeExport.cardBg??derivedExportColors.cardBg,infoBg=themeExport.infoBg??derivedExportColors.infoBg,sessionDataBase64=Buffer.from(JSON.stringify(sessionData)).toString("base64"),css=templateCss.replace("{{THEME_VARS}}",themeVars).replace("{{BODY_BG}}",bodyBg).replace("{{CONTAINER_BG}}",containerBg).replace("{{INFO_BG}}",infoBg);return template.replace("{{CSS}}",css).replace("{{JS}}",templateJs).replace("{{SESSION_DATA}}",sessionDataBase64).replace("{{MARKED_JS}}",markedJs).replace("{{HIGHLIGHT_JS}}",hljsJs)}var TEMPLATE_RENDERED_TOOLS=new Set(["bash","read","write","edit","ls"]);function preRenderCustomTools(entries,toolRenderer){let renderedTools={};for(let entry of entries){if(entry.type!=="message")continue;let msg=entry.message;if(msg.role==="assistant"&&Array.isArray(msg.content)){for(let block of msg.content)if(block.type==="toolCall"&&!TEMPLATE_RENDERED_TOOLS.has(block.name)){let callHtml=toolRenderer.renderCall(block.id,block.name,block.arguments);callHtml&&(renderedTools[block.id]={callHtml})}}if(msg.role==="toolResult"&&msg.toolCallId){let toolName=msg.toolName||"",existing=renderedTools[msg.toolCallId];if(existing||!TEMPLATE_RENDERED_TOOLS.has(toolName)){let rendered=toolRenderer.renderResult(msg.toolCallId,toolName,msg.content,msg.details,msg.isError||!1);rendered&&(renderedTools[msg.toolCallId]={...existing,resultHtmlCollapsed:rendered.collapsed,resultHtmlExpanded:rendered.expanded})}}}return renderedTools}async function exportSessionToHtml(sm,state2,options){let opts=typeof options=="string"?{outputPath:options}:options||{},sessionFile=sm.getSessionFile();if(!sessionFile)throw new Error("Cannot export in-memory session to HTML");if(!existsSync10(sessionFile))throw new Error("Nothing to export yet - start a conversation first");let entries=sm.getEntries(),renderedTools;opts.toolRenderer&&(renderedTools=preRenderCustomTools(entries,opts.toolRenderer),Object.keys(renderedTools).length===0&&(renderedTools=void 0));let sessionData={header:sm.getHeader(),entries,leafId:sm.getLeafId(),systemPrompt:state2?.systemPrompt,tools:state2?.tools?.map(t=>({name:t.name,description:t.description,parameters:t.parameters})),renderedTools},html=generateHtml(sessionData,opts.themeName),outputPath=opts.outputPath?normalizePath(opts.outputPath):void 0;if(!outputPath){let sessionBasename=basename8(sessionFile,".jsonl");outputPath=`${APP_NAME}-session-${sessionBasename}.html`}return writeFileSync7(outputPath,html,"utf8"),outputPath}async function exportFromFile(inputPath,options){let opts=typeof options=="string"?{outputPath:options}:options||{},resolvedInputPath=resolvePath(inputPath);if(!existsSync10(resolvedInputPath))throw new Error(`File not found: ${resolvedInputPath}`);let sm=SessionManager.open(resolvedInputPath),sessionData={header:sm.getHeader(),entries:sm.getEntries(),leafId:sm.getLeafId(),systemPrompt:void 0,tools:void 0},html=generateHtml(sessionData,opts.themeName),outputPath=opts.outputPath?normalizePath(opts.outputPath):void 0;if(!outputPath){let inputBasename=basename8(resolvedInputPath,".jsonl");outputPath=`${APP_NAME}-session-${inputBasename}.html`}return writeFileSync7(outputPath,html,"utf8"),outputPath}var ANSI_COLORS=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff"];function color256ToHex(index3){if(index3<16)return ANSI_COLORS[index3];if(index3<232){let cubeIndex=index3-16,r=Math.floor(cubeIndex/36),g2=Math.floor(cubeIndex%36/6),b2=cubeIndex%6,toComponent=n=>n===0?0:55+n*40,toHex=n=>toComponent(n).toString(16).padStart(2,"0");return`#${toHex(r)}${toHex(g2)}${toHex(b2)}`}let grayHex=(8+(index3-232)*10).toString(16).padStart(2,"0");return`#${grayHex}${grayHex}${grayHex}`}function escapeHtml(text){return text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function createEmptyStyle(){return{fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1}}function styleToInlineCSS(style){let parts=[];return style.fg&&parts.push(`color:${style.fg}`),style.bg&&parts.push(`background-color:${style.bg}`),style.bold&&parts.push("font-weight:bold"),style.dim&&parts.push("opacity:0.6"),style.italic&&parts.push("font-style:italic"),style.underline&&parts.push("text-decoration:underline"),parts.join(";")}function hasStyle(style){return style.fg!==null||style.bg!==null||style.bold||style.dim||style.italic||style.underline}function applySgrCode(params,style){let i=0;for(;i<params.length;){let code=params[i];if(code===0)style.fg=null,style.bg=null,style.bold=!1,style.dim=!1,style.italic=!1,style.underline=!1;else if(code===1)style.bold=!0;else if(code===2)style.dim=!0;else if(code===3)style.italic=!0;else if(code===4)style.underline=!0;else if(code===22)style.bold=!1,style.dim=!1;else if(code===23)style.italic=!1;else if(code===24)style.underline=!1;else if(code>=30&&code<=37)style.fg=ANSI_COLORS[code-30];else if(code===38){if(params[i+1]===5&¶ms.length>i+2)style.fg=color256ToHex(params[i+2]),i+=2;else if(params[i+1]===2&¶ms.length>i+4){let r=params[i+2],g2=params[i+3],b2=params[i+4];style.fg=`rgb(${r},${g2},${b2})`,i+=4}}else if(code===39)style.fg=null;else if(code>=40&&code<=47)style.bg=ANSI_COLORS[code-40];else if(code===48){if(params[i+1]===5&¶ms.length>i+2)style.bg=color256ToHex(params[i+2]),i+=2;else if(params[i+1]===2&¶ms.length>i+4){let r=params[i+2],g2=params[i+3],b2=params[i+4];style.bg=`rgb(${r},${g2},${b2})`,i+=4}}else code===49?style.bg=null:code>=90&&code<=97?style.fg=ANSI_COLORS[code-90+8]:code>=100&&code<=107&&(style.bg=ANSI_COLORS[code-100+8]);i++}}var ANSI_REGEX=/\x1b\[([\d;]*)m/g;function ansiToHtml(text){let style=createEmptyStyle(),result="",lastIndex=0,inSpan=!1;ANSI_REGEX.lastIndex=0;let match2=ANSI_REGEX.exec(text);for(;match2!==null;){let beforeText=text.slice(lastIndex,match2.index);beforeText&&(result+=escapeHtml(beforeText));let paramStr=match2[1],params=paramStr?paramStr.split(";").map(p=>parseInt(p,10)||0):[0];inSpan&&(result+="</span>",inSpan=!1),applySgrCode(params,style),hasStyle(style)&&(result+=`<span style="${styleToInlineCSS(style)}">`,inSpan=!0),lastIndex=match2.index+match2[0].length,match2=ANSI_REGEX.exec(text)}let remainingText=text.slice(lastIndex);return remainingText&&(result+=escapeHtml(remainingText)),inSpan&&(result+="</span>"),result}function ansiLinesToHtml(lines){return lines.map(line=>`<div class="ansi-line">${ansiToHtml(line)||" "}</div>`).join("")}var ANSI_ESCAPE_REGEX=/\x1b\[[\d;]*m/g;function isBlankRenderedLine(line){return line.replace(ANSI_ESCAPE_REGEX,"").trim().length===0}function trimRenderedResultLines(lines){let start=0,end=lines.length;for(;start<end&&isBlankRenderedLine(lines[start]);)start++;for(;end>start&&isBlankRenderedLine(lines[end-1]);)end--;return lines.slice(start,end)}function createToolHtmlRenderer(deps){let{getToolDefinition:getToolDefinition2,theme:theme2,cwd,width=100}=deps,renderedCallComponents=new Map,renderedResultComponents=new Map,renderedStates=new Map,renderedArgs=new Map,getState=toolCallId=>{let state2=renderedStates.get(toolCallId);return state2||(state2={},renderedStates.set(toolCallId,state2)),state2},createRenderContext=(toolCallId,lastComponent,expanded,isPartial,isError)=>({args:renderedArgs.get(toolCallId),toolCallId,invalidate:()=>{},lastComponent,state:getState(toolCallId),cwd,executionStarted:!0,argsComplete:!0,isPartial,expanded,showImages:!1,isError});return{renderCall(toolCallId,toolName,args){try{renderedArgs.set(toolCallId,args);let toolDef=getToolDefinition2(toolName);if(!toolDef?.renderCall)return;let component=toolDef.renderCall(args,theme2,createRenderContext(toolCallId,renderedCallComponents.get(toolCallId),!1,!0,!1));renderedCallComponents.set(toolCallId,component);let lines=component.render(width);return ansiLinesToHtml(lines)}catch{return}},renderResult(toolCallId,toolName,result,details,isError){try{let toolDef=getToolDefinition2(toolName);if(!toolDef?.renderResult)return;let agentToolResult={content:result,details,isError},collapsedComponent=toolDef.renderResult(agentToolResult,{expanded:!1,isPartial:!1},theme2,createRenderContext(toolCallId,renderedResultComponents.get(toolCallId),!1,!1,isError));renderedResultComponents.set(toolCallId,collapsedComponent);let collapsed=ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width))),expandedComponent=toolDef.renderResult(agentToolResult,{expanded:!0,isPartial:!1},theme2,createRenderContext(toolCallId,renderedResultComponents.get(toolCallId),!0,!1,isError));renderedResultComponents.set(toolCallId,expandedComponent);let expanded=ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));return{...collapsed&&collapsed!==expanded?{collapsed}:{},expanded}}catch{return}}}}import{existsSync as existsSync11,mkdirSync as mkdirSync9,writeFileSync as writeFileSync8}from"node:fs";import{dirname as dirname18}from"node:path";function serializeSessionBranch(sessionManager,header,createTrailingEntries){let lines=[JSON.stringify(header)],parentId=null;for(let entry of sessionManager.getBranch())lines.push(JSON.stringify({...entry,parentId})),parentId=entry.id;for(let entry of createTrailingEntries?.(parentId,header.timestamp)??[])lines.push(JSON.stringify(entry));return`${lines.join(`
|
|
987
987
|
`)}
|
|
988
988
|
`}function createSessionJsonlArtifact(sessionManager){let header=sessionManager.getHeader();if(!header)throw new Error("Cannot export a session without a session header");return{version:1,format:"jsonl",mediaType:"application/x-ndjson",fileName:`session-${header.id}.jsonl`,bytes:new TextEncoder().encode(serializeSessionBranch(sessionManager,{...header}))}}function exportSessionToJsonl(sessionManager,outputPath,createTrailingEntries){let filePath=resolvePath(outputPath??`session-${new Date().toISOString().replace(/[:.]/g,"-")}.jsonl`,process.cwd()),dir=dirname18(filePath);existsSync11(dir)||mkdirSync9(dir,{recursive:!0});let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:sessionManager.getSessionId(),timestamp,cwd:sessionManager.getCwd()};return writeFileSync8(filePath,serializeSessionBranch(sessionManager,header,createTrailingEntries)),filePath}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite,totals})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b2)=>b2.cost-a.cost)}function getUserMessagesForForking(session){let entries=session.sessionManager.getEntries(),result=[];for(let entry of entries){if(entry.type!=="message"||entry.message.role!=="user")continue;let text=contentText(entry.message.content,"");text&&result.push({entryId:entry.id,text})}return result}function getSessionStats(session){let userMessages=0,assistantMessages=0,toolResults=0,totalMessages=0,toolCalls=0,usageTotals=createUsageTotals();for(let entry of session.sessionManager.getEntries()){if((entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&addUsageToTotals(usageTotals,entry.usage),entry.type!=="message")continue;totalMessages++;let message=entry.message;if(message.role==="user")userMessages++;else if(message.role==="toolResult")toolResults++,message.usage&&addUsageToTotals(usageTotals,message.usage);else if(message.role==="assistant"){assistantMessages++;let assistantMsg=message;Array.isArray(assistantMsg.content)&&(toolCalls+=assistantMsg.content.filter(c2=>c2.type==="toolCall").length),addUsageToTotals(usageTotals,assistantMsg.usage)}}return{sessionFile:session.sessionFile,sessionId:session.sessionId,userMessages,assistantMessages,toolCalls,toolResults,totalMessages,tokens:{input:usageTotals.input,output:usageTotals.output,cacheRead:usageTotals.cacheRead,cacheWrite:usageTotals.cacheWrite,total:usageTotals.input+usageTotals.output+usageTotals.cacheRead+usageTotals.cacheWrite},cost:usageTotals.cost,contextUsage:session.getContextUsage()}}function getContextUsage(session){let model=session.model;if(!model)return;let contextWindow=model.contextWindow??0;if(contextWindow<=0)return;let branchEntries=session.sessionManager.getBranch(),latestCompaction=getLatestCompactionEntry(branchEntries);if(latestCompaction){let compactionIndex=branchEntries.lastIndexOf(latestCompaction),hasPostCompactionUsage=!1;for(let i=branchEntries.length-1;i>compactionIndex;i--){let entry=branchEntries[i];if(entry.type==="message"&&entry.message.role==="assistant"){let assistant=entry.message;if(assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens2(assistant.usage)>0){hasPostCompactionUsage=!0;break}}}if(!hasPostCompactionUsage)return{tokens:null,contextWindow,percent:null}}let estimate=estimateContextTokens2(session.messages),percent=estimate.tokens/contextWindow*100;return{tokens:estimate.tokens,contextWindow,percent}}async function exportToHtml(session,outputPath,options={}){let themeName=[options.themeName,session.settingsManager.getTheme()].find(candidate=>candidate!==void 0&&getThemeByName(candidate)!==void 0),toolRenderer=createToolHtmlRenderer({getToolDefinition:name=>session.getToolDefinition(name),theme,cwd:session.sessionManager.getCwd()});return await exportSessionToHtml(session.sessionManager,session.agent.state,{outputPath,themeName,toolRenderer})}function exportToJsonl(session,outputPath){return exportSessionToJsonl(session.sessionManager,outputPath)}function getLastAssistantText(session){let lastAssistant=session.messages.slice().reverse().find(m2=>{if(m2.role!=="assistant")return!1;let msg=m2;return!(msg.stopReason==="aborted"&&msg.content.length===0)});if(!lastAssistant)return;let text="";for(let content of lastAssistant.content)content.type==="text"&&(text+=content.text);return text.trim()||void 0}function sleep3(ms,signal){return new Promise((resolve25,reject2)=>{if(signal?.aborted){reject2(new Error("Aborted"));return}let timeout=setTimeout(resolve25,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject2(new Error("Aborted"))})})}async function willRetryAfterAgentEnd(session,event,signal){if(signal?.aborted)return session._pendingRetryDecision=void 0,!1;let settings2=session.settingsManager.getRetrySettings();if(session._retryAttempt>=settings2.maxRetries)return session._pendingRetryDecision=void 0,!1;for(let i=event.messages.length-1;i>=0;i--){let message=event.messages[i];if(message.role==="assistant"){let assistantMessage=message;try{let decision=await decideRetry(session,assistantMessage,void 0,signal);return session._pendingRetryDecision={message:assistantMessage,decision},decision.retry}catch(error2){if(signal?.aborted)return session._pendingRetryDecision=void 0,!1;throw error2}}}return session._pendingRetryDecision=void 0,!1}async function isRetryableError(session,message,execution,signal){if((await decideOverflow(session,message,execution,signal)).contextOverflow)return!1;let runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return runtime.classifyRetry(session._retryPolicyName,{message,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution:execution??executionFacts(session,"retry")})}async function decideRetry(session,message,execution,signal){let settings2=session.settingsManager.getRetrySettings(),runtime=session._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");return runtime.decideRetry(session._retryPolicyName,{retryable:await session._isRetryableError(message,execution,signal),enabled:settings2.enabled,attempt:session._retryAttempt+1,maxAttempts:settings2.maxRetries,baseDelayMs:settings2.baseDelayMs,errorMessage:message.errorMessage,signal,context:{version:1,sessionId:session.sessionId,phase:"retry"},execution:execution??executionFacts(session,"retry")})}async function prepareRetry(session,message,precomputedDecision){let settings2=session.settingsManager.getRetrySettings(),decision=precomputedDecision??await decideRetry(session,message);if(!decision.retry)return!1;session._retryAttempt++;let baseDelayMs=Math.min(decision.delayMs??retryDelayMs(settings2,session._retryAttempt),settings2.maxAgentDelayMs),delayMs=Math.round(baseDelayMs*(.9+Math.random()*.2));session._retryAbortController=new AbortController,session._emit({type:"auto_retry_start",attempt:session._retryAttempt,maxAttempts:settings2.maxRetries,delayMs,errorMessage:message.errorMessage||"Unknown error"}),await dispatchAutoRetryLifecycle(session,{attempt:session._retryAttempt,maxAttempts:settings2.maxRetries,delayMs,errorMessage:message.errorMessage||"Unknown error"});let messages=session.agent.state.messages;messages.length>0&&messages[messages.length-1].role==="assistant"&&await session._applyContextTransition(messages.slice(0,-1),"retry");try{await sleep3(delayMs,session._retryAbortController.signal)}catch{let attempt2=session._retryAttempt;return session._retryAttempt=0,session._emit({type:"auto_retry_end",success:!1,attempt:attempt2,finalError:"Retry cancelled"}),!1}finally{session._retryAbortController=void 0}return!0}function buildSystemPrompt(options){let{customPrompt,orientationPrompt,preferenceCard,selectedTools,toolSnippets,promptGuidelines,appendSystemPrompt,cwd,contextFiles:providedContextFiles,skills:providedSkills}=options,promptCwd=cwd.replace(/\\/g,"/"),appendSection=appendSystemPrompt?`
|
|
@@ -1047,7 +1047,7 @@ Current working directory: ${promptCwd}`,prompt}function normalizePromptSnippet(
|
|
|
1047
1047
|
`):void 0,loadedSkills=session._getAvailableSkills(),loadedContextFiles=session._resourceLoader.getAgentsFiles().agentsFiles;return session._baseSystemPromptOptions={cwd:session._cwd,skills:loadedSkills,contextFiles:loadedContextFiles,customPrompt:loaderSystemPrompt,orientationPrompt:session._orientationPrompt,preferenceCard:session._preferenceCard,appendSystemPrompt,selectedTools:validToolNames,toolSnippets,promptGuidelines},buildSystemPrompt(session._baseSystemPromptOptions)}function refreshToolRegistry(session,options){let previousRegistryNames=new Set(session._toolRegistry.keys()),previousActiveToolNames=session.getActiveToolNames(),allowedToolNames=session._allowedToolNames,excludedToolNames=session._excludedToolNames,isAllowedTool=name=>(!allowedToolNames||allowedToolNames.has(name))&&!excludedToolNames?.has(name),allCustomTools=session._customTools.map(definition=>({definition,sourceInfo:createSyntheticSourceInfo(`<sdk:${definition.name}>`,{source:"sdk"})})).filter(tool=>isAllowedTool(tool.definition.name)),definitionRegistry=new Map(Array.from(session._baseToolDefinitions.entries()).filter(([name])=>isAllowedTool(name)).map(([name,definition])=>[name,{definition,sourceInfo:session._baseToolSources.get(name)??createSyntheticSourceInfo(`<bootstrap:${name}>`,{source:"agent-forge.bootstrap-tools"})}]));for(let tool of allCustomTools)definitionRegistry.set(tool.definition.name,{definition:tool.definition,sourceInfo:tool.sourceInfo});session._toolDefinitions=definitionRegistry,session._toolPromptSnippets=new Map(Array.from(definitionRegistry.values()).map(({definition})=>{let snippet=normalizePromptSnippet(definition.promptSnippet);return snippet?[definition.name,snippet]:void 0}).filter(entry=>entry!==void 0)),session._toolPromptGuidelines=new Map(Array.from(definitionRegistry.values()).map(({definition})=>{let guidelines=normalizePromptGuidelines(definition.promptGuidelines);return guidelines.length>0?[definition.name,guidelines]:void 0}).filter(entry=>entry!==void 0));let executeContext=()=>({cwd:session.sessionManager.getCwd(),model:session.model,sessionManager:session.sessionManager,thinkingLevel:session.thinkingLevel}),wrapWithDynamicToolTracking=({definition})=>{let tool=wrapToolDefinition(definition,executeContext),execute=tool.execute;return{...tool,execute:async(toolCallId,params,signal,onUpdate)=>{let activeBefore=session.getActiveToolNames(),result=await execute(toolCallId,params,signal,onUpdate),activeAfter=session.getActiveToolNames();if(!activeBefore.every(name=>activeAfter.includes(name)))return result;let beforeNames=new Set(activeBefore),addedToolNames=activeAfter.filter(name=>!beforeNames.has(name));return addedToolNames.length===0?result:{...result,addedToolNames:[...new Set([...result.addedToolNames??[],...addedToolNames])]}}}},wrappedExtensionTools=allCustomTools.map(wrapWithDynamicToolTracking),wrappedBuiltInTools=Array.from(session._baseToolDefinitions.values()).filter(definition=>isAllowedTool(definition.name)).map(definition=>wrapWithDynamicToolTracking({definition})),toolRegistry=new Map(wrappedBuiltInTools.map(tool=>[tool.name,tool]));for(let tool of wrappedExtensionTools)toolRegistry.set(tool.name,tool);session._toolRegistry=toolRegistry;let nextActiveToolNames=(options?.activeToolNames?[...options.activeToolNames]:[...previousActiveToolNames]).filter(name=>isAllowedTool(name));if(allowedToolNames)for(let toolName of session._toolRegistry.keys())allowedToolNames.has(toolName)&&nextActiveToolNames.push(toolName);else if(options?.includeAllExtensionTools)for(let tool of wrappedExtensionTools)nextActiveToolNames.push(tool.name);else if(!options?.activeToolNames)for(let toolName of session._toolRegistry.keys())previousRegistryNames.has(toolName)||session._deferredToolPluginIds.has(session._baseToolSources.get(toolName)?.source??"")||nextActiveToolNames.push(toolName);session.setActiveToolsByName([...new Set(nextActiveToolNames)])}function syncCapabilityTools(session){let tools=session._capabilityRuntime?.listTools()??[];session._baseToolDefinitions=new Map(tools.map(({name,definition})=>[name,definition])),session._baseToolSources=new Map(tools.map(({name,source})=>[name,createSyntheticSourceInfo(`<plugin:${source}:${name}>`,{source})]))}function getCapabilitySkills(session){let runtime=session._capabilityRuntime;if(!runtime)return[];let contributed;try{contributed=runtime.listContributions(SKILL_CONTRIBUTION_POINT_ID,SKILL_CONTRIBUTION_POINT_VERSION)}catch(error2){if(!(error2 instanceof Error)||!error2.message.startsWith("Contribution point is not defined"))throw error2;return[]}let contributedSkills=contributed.filter(entry=>entry.value!==null&&typeof entry.value=="object"&&"name"in entry.value).map(entry=>({...entry.value,disableModelInvocation:entry.value.disableModelInvocation===!0,sourceInfo:createSyntheticSourceInfo(`<contribution:${entry.owner}:${entry.id}>`,{source:entry.owner,baseDir:entry.value.baseDir})})),contributedNames=new Set(contributedSkills.map(skill=>skill.name)),legacyFilter=session._capabilitySkillsFilter,legacy=runtime.listSkills().filter(({definition})=>!contributedNames.has(definition.name)).map(({definition,source})=>({...definition,disableModelInvocation:definition.disableModelInvocation===!0,sourceInfo:createSyntheticSourceInfo(`<plugin:${source}:${definition.name}>`,{source,baseDir:definition.baseDir})})).filter(skill=>legacyFilter?legacyFilter([skill]).length>0:!0);return[...contributedSkills,...legacy].sort((left,right)=>left.name.localeCompare(right.name)||left.sourceInfo.path.localeCompare(right.sourceInfo.path))}function validateCapabilitySkillConflicts(session){let resourceNames=new Set,resourceFilePaths=new Set;for(let skill of session._resourceLoader.getSkills().skills){if(resourceNames.has(skill.name))throw new Error(`Skill is duplicated in resources: ${skill.name}`);resourceNames.add(skill.name),resourceFilePaths.add(skill.filePath)}for(let skill of session._getCapabilitySkills())if(!(typeof skill.filePath=="string"&&resourceFilePaths.has(skill.filePath))&&resourceNames.has(skill.name))throw new Error(`Skill conflicts with a resource skill: ${skill.name}`)}async function refreshBootstrapSkills(session){let runtime=session._capabilityRuntime;runtime&&(session._validateCapabilitySkillConflicts(),session._bootstrapSkillsHandle?await refreshSessionBootstrapSkills(runtime,session._resourceLoader.getSkills().skills):session._bootstrapSkillsHandle=installSessionBootstrapSkills(runtime,session._resourceLoader.getSkills().skills),session._baseSystemPrompt=session._rebuildSystemPrompt(session.getActiveToolNames()),session.agent.state.systemPrompt=session._baseSystemPrompt)}import{existsSync as existsSync12,readdirSync as readdirSync10,readFileSync as readFileSync10,statSync as statSync10}from"fs";import{basename as basename9,dirname as dirname19,join as join37,resolve as resolve10,sep as sep7}from"path";function parseCommandArgs(argsString){let args=[],current="",inQuote=null;for(let i=0;i<argsString.length;i++){let char=argsString[i];inQuote?char===inQuote?inQuote=null:current+=char:char==='"'||char==="'"?inQuote=char:/\s/.test(char)?current&&(args.push(current),current=""):current+=char}return current&&args.push(current),args}function substituteArgs(content,args){let allArgs=args.join(" ");return content.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(_match,defaultTarget,defaultValue,sliceStart,sliceLength,simple)=>{if(defaultTarget){let value=defaultTarget==="@"||defaultTarget==="ARGUMENTS"?allArgs:args[parseInt(defaultTarget,10)-1];return value||defaultValue}if(sliceStart){let start=parseInt(sliceStart,10)-1;if(start<0&&(start=0),sliceLength){let length=parseInt(sliceLength,10);return args.slice(start,start+length).join(" ")}return args.slice(start).join(" ")}if(simple==="ARGUMENTS"||simple==="@")return allArgs;let index3=parseInt(simple,10)-1;return args[index3]??""})}function loadTemplateFromFile(filePath,sourceInfo){try{let rawContent=readFileSync10(filePath,"utf-8"),{frontmatter,body}=parseFrontmatter(rawContent),name=basename9(filePath).replace(/\.md$/,""),description=frontmatter.description||"";if(!description){let firstLine=body.split(`
|
|
1048
1048
|
`).find(line=>line.trim());firstLine&&(description=firstLine.slice(0,60),firstLine.length>60&&(description+="..."))}return{name,description,...frontmatter["argument-hint"]&&{argumentHint:frontmatter["argument-hint"]},content:body,sourceInfo,filePath}}catch{return null}}function loadTemplatesFromDir(dir,getSourceInfo){let templates=[];if(!existsSync12(dir))return templates;try{let entries=readdirSync10(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=join37(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync10(fullPath).isFile()}catch{continue}if(isFile&&entry.name.endsWith(".md")){let template=loadTemplateFromFile(fullPath,getSourceInfo(fullPath));template&&templates.push(template)}}}catch{return templates}return templates}function loadPromptTemplates(options){let resolvedCwd=resolvePath(options.cwd),resolvedAgentDir=resolvePath(options.agentDir),promptPaths=options.promptPaths,includeDefaults=options.includeDefaults,templates=[],globalPromptsDir=join37(resolvedAgentDir,"prompts"),projectPromptsDir=resolve10(resolvedCwd,CONFIG_DIR_NAME,"prompts"),isUnderPath=(target,root)=>{let normalizedRoot=resolve10(root);if(target===normalizedRoot)return!0;let prefix=normalizedRoot.endsWith(sep7)?normalizedRoot:`${normalizedRoot}${sep7}`;return target.startsWith(prefix)},getSourceInfo=resolvedPath=>isUnderPath(resolvedPath,globalPromptsDir)?createSyntheticSourceInfo(resolvedPath,{source:"local",scope:"user",baseDir:globalPromptsDir}):isUnderPath(resolvedPath,projectPromptsDir)?createSyntheticSourceInfo(resolvedPath,{source:"local",scope:"project",baseDir:projectPromptsDir}):createSyntheticSourceInfo(resolvedPath,{source:"local",baseDir:statSync10(resolvedPath).isDirectory()?resolvedPath:dirname19(resolvedPath)});includeDefaults&&(templates.push(...loadTemplatesFromDir(globalPromptsDir,getSourceInfo)),templates.push(...loadTemplatesFromDir(projectPromptsDir,getSourceInfo)));for(let rawPath of promptPaths){let resolvedPath=resolvePath(rawPath,resolvedCwd,{trim:!0});if(existsSync12(resolvedPath))try{let stats=statSync10(resolvedPath);if(stats.isDirectory())templates.push(...loadTemplatesFromDir(resolvedPath,getSourceInfo));else if(stats.isFile()&&resolvedPath.endsWith(".md")){let template=loadTemplateFromFile(resolvedPath,getSourceInfo(resolvedPath));template&&templates.push(template)}}catch{}}return templates}function expandPromptTemplate(text,templates){if(!text.startsWith("/"))return text;let match2=text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!match2)return text;let templateName=match2[1],argsString=match2[2]??"",template=templates.find(t=>t.name===templateName);if(template){let args=parseCommandArgs(argsString);return substituteArgs(template.content,args)}return text}var toolSearchParameters=typebox_exports.Object({query:typebox_exports.String({description:"Search text matched against tool names and descriptions."}),limit:typebox_exports.Optional(typebox_exports.Number({description:"Maximum number of matches to activate. Defaults to 5.",minimum:1,maximum:20}))});function scoreTool(name,description,terms){let lowerName=name.toLowerCase(),lowerDescription=description.toLowerCase(),score=0;for(let term of terms)lowerName===term?score+=8:lowerName.startsWith(term)?score+=4:lowerName.includes(term)&&(score+=2),lowerDescription.includes(term)&&(score+=1);return score>0?score:void 0}function createToolSearchTool(deps){return{name:"tool_search",label:"Tool search",description:"Search for available tools by name or description and activate the matches so they can be called. Use this when a capability you need is not in the current tool list.",promptSnippet:"Search and activate deferred tools (used when a needed capability is not currently available)",parameters:toolSearchParameters,execute:async(_toolCallId,params)=>{let query=params.query.trim();if(query.length===0)return{content:[{type:"text",text:"Provide a non-empty query."}],details:{activated:[]}};let terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>0),activeNames=new Set(deps.getActiveToolNames()),matches=[];for(let name of deps.listAllToolNames()){let info=deps.getToolInfo(name);if(!info||activeNames.has(name))continue;let score=scoreTool(name,info.description,terms);score!==void 0&&matches.push({name,score})}matches.sort((left,right)=>right.score-left.score||left.name.localeCompare(right.name));let limit=params.limit??5,activated=matches.slice(0,limit).map(match2=>match2.name);if(activated.length===0)return{content:[{type:"text",text:`No inactive tools match "${query}".`}],details:{activated:[]}};deps.setActiveToolsByName([...deps.getActiveToolNames(),...activated]);let lines=activated.map(name=>{let info=deps.getToolInfo(name);return`- ${name}: ${info?.description??""}`});return{content:[{type:"text",text:`Activated ${activated.length} tool(s). They are now available for tool calls:
|
|
1049
1049
|
${lines.join(`
|
|
1050
|
-
`)}`}],details:{activated}}}}}function parseSkillBlock(text){let match2=text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return match2?{name:match2[1],location:match2[2],content:match2[3],userMessage:match2[4]?.trim()||void 0}:null}var SUITE_MISMATCH_SESSION_ENTRY_TYPE="suite_mismatch",AgentSession=class{agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionQueue=Promise.resolve();_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_overflowTrimStage=0;_branchSummaryAbortController=void 0;_branchSummaryPromise=void 0;_resolveBranchSummaryPromise=void 0;_retryAbortController=void 0;_policyDecisionAbortController=void 0;_retryAttempt=0;_commandAbortController=void 0;_agentTaskScopeAbortController=new AbortController;_activeCapabilityCommand;_activeCompactionPromise;_reloadInProgress=!1;_reloadGeneration=0;_contextEpoch=0;_contextTransitionAbortController=new AbortController;_activeContextTransition;_contextRevision=0;_contextCommitQueue=Promise.resolve();_bashAbortControllers=new Set;_activeBashPromises=new Set;_bashEpoch=0;_pendingBashMessages=[];_turnIndex=0;_resourceLoader;_customTools;_deferredToolPluginIds;_pendingAbortReason;_currentRunAborted=!1;_lastAbortReason;_baseToolDefinitions=new Map;_baseToolSources=new Map;_capabilityRuntime;_outputArtifactCommitListeners=new Set;_dispatchOutputArtifactCommit=artifact=>{for(let listener of[...this._outputArtifactCommitListeners])listener(artifact)};_bootstrapToolsHandle;_bootstrapSkillsHandle;_bootstrapRetryHandle;_bootstrapCompactionHandle;_bootstrapBranchSummaryHandle;_bootstrapOverflowHandle;_bootstrapAgentLoopHandle;_bootstrapLifecycleHandle;_capabilityPlugins=new Map;_inlineCapabilityPlugins=new Map;_isDisposingCapabilityPlugins=!1;_suspendToolRegistryHookRefresh=!1;_toolRegistryHookReady=!1;_disposePromise;_cwd;_initialActiveToolNames;_allowedToolNames;_excludedToolNames;_baseToolsOverride;_disabledBootstrapPlugins;_sessionStartEvent;_capabilityMode;_contextStrategyName;_retryPolicyName;_compactionPolicyName;_branchSummaryPolicyName;_overflowPolicyName;_runLoopStrategyName;_loopExecutor;_initialPrepareNextTurn;_agentTaskAdapter;_agentTaskResults;_agentSessionReader;_agentSessionLister;_agentComposition;_interactionHost;_modelRuntime;_modelStreamCounter=0;_modelStreamState;_turnCorrelationId;_turnCorrelationCounter=0;_toolRegistry=new Map;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPrompt="";_baseSystemPromptOptions;_systemPromptOverride;_orientationPrompt;_preferenceCard;_capabilitySkillsFilter;_hostLogger;_logRecordMirrorRef;_observabilityGetMetricsRef;_agentDir;_communication;_turnContext;_roleAssociations;_memoryStorage;_traceService;constructor(config){this.agent=config.agent,this.sessionManager=config.sessionManager,this._contextRevision=this.sessionManager.getRevision().sequence,this.settingsManager=config.settingsManager,this._scopedModels=config.scopedModels??[],this._resourceLoader=config.resourceLoader,this._customTools=config.customTools??[],this._deferredToolPluginIds=new Set(config.deferredToolPluginIds??[]),this._deferredToolPluginIds.size>0&&this._customTools.push(createToolSearchTool({listAllToolNames:()=>Array.from(this._toolRegistry.keys()),getToolInfo:name=>{let definition=this._toolDefinitions.get(name)?.definition;return definition?{name:definition.name,description:definition.description}:void 0},getActiveToolNames:()=>this.getActiveToolNames(),setActiveToolsByName:toolNames=>this.setActiveToolsByName(toolNames)})),this._cwd=config.cwd,this._modelRuntime=config.modelRuntime,this._initialActiveToolNames=config.initialActiveToolNames,this._allowedToolNames=config.allowedToolNames?new Set(config.allowedToolNames):void 0,this._excludedToolNames=config.excludedToolNames?new Set(config.excludedToolNames):void 0,this._baseToolsOverride=config.baseToolsOverride,this._disabledBootstrapPlugins=config.disabledBootstrapPlugins,this._sessionStartEvent=config.sessionStartEvent??{reason:"startup"},this._capabilityMode=config.capabilityMode??"full-control",this._contextStrategyName=config.contextStrategyName,this._retryPolicyName=config.retryPolicyName??DEFAULT_RETRY_POLICY_NAME,this._compactionPolicyName=config.compactionPolicyName??DEFAULT_COMPACTION_POLICY_NAME,this._branchSummaryPolicyName=config.branchSummaryPolicyName??DEFAULT_BRANCH_SUMMARY_POLICY_NAME,this._overflowPolicyName=config.overflowPolicyName??DEFAULT_OVERFLOW_POLICY_NAME,this._runLoopStrategyName=config.runLoopStrategyName??DEFAULT_RUN_LOOP_STRATEGY_NAME,this._agentTaskAdapter=config.agentTaskAdapter,this._agentTaskResults=config.agentTaskResults,this._agentSessionReader=config.agentSessionReader,this._agentSessionLister=config.agentSessionLister,this._agentComposition=config.agentComposition,this._interactionHost=config.interactionHost,this._orientationPrompt=config.orientationPrompt,this._preferenceCard=config.preferenceCard,this._capabilitySkillsFilter=config.capabilitySkillsFilter,this._hostLogger=config.hostLogger,this._logRecordMirrorRef=config.logRecordMirrorRef,this._observabilityGetMetricsRef=config.observabilityGetMetricsRef,this._agentDir=config.agentDir,this._communication=config.communication,this._turnContext=config.turnContext,this._roleAssociations=config.roleAssociations,this._memoryStorage=config.memoryStorage,this._traceService=config.traceService,this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._wireDefaultLoop()}getTurnCorrelationId(){return this._turnCorrelationId}dispatchAgentTaskSettled(facts){dispatchAgentTaskSettledLifecycle(this._internal,facts)}get modelRuntime(){return this._modelRuntime}get _internal(){return this}_wireDefaultLoop(){wireDefaultLoop(this._internal)}_createLoopWiring(){return createLoopWiring(this._internal)}_compactBeforeNextAssistantResponse(context,signal){return compactBeforeNextAssistantResponse(this._internal,context,signal)}_emit(event){for(let l3 of this._eventListeners)l3(event)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(resolve25=>{this._resolveIdleWait=resolve25})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;let resolve25=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,resolve25()}async _emitAgentSettled(){this._isAgentRunActive=!1;try{this._emit({type:"agent_settled"}),await dispatchAgentSettledLifecycle(this._internal)}finally{this._resolveIdleWaitIfIdle()}}_lastAssistantMessage=void 0;_pendingRetryDecision=void 0;_handleAgentEvent=async event=>{if(event.type==="message_start"&&event.message.role==="assistant"&&(this._modelStreamState={streamId:`model-stream:${++this._modelStreamCounter}`,sequence:0},await this._dispatchModelStreamLifecycle(event.message,"start","raw")),event.type==="message_start"&&event.message.role==="user"){this._overflowRecoveryAttempted=!1,this._overflowTrimStage=0;let messageText=contentText(event.message.content,"");if(messageText){let steeringIndex=this._steeringMessages.indexOf(messageText);if(steeringIndex!==-1)this._steeringMessages.splice(steeringIndex,1),this._emitQueueUpdate();else{let followUpIndex=this._followUpMessages.indexOf(messageText);followUpIndex!==-1&&(this._followUpMessages.splice(followUpIndex,1),this._emitQueueUpdate())}}}if(await this._emitLifecycleEvents(event),event.type==="message_update"&&event.message.role==="assistant"&&await this._dispatchModelStreamLifecycle(event.message,event.assistantMessageEvent.type,"candidate"),this._emit(event.type==="agent_end"?{...event,willRetry:await this._willRetryAfterAgentEnd(event,this._policyDecisionAbortController?.signal)}:event),event.type==="message_end"){if(event.message.role==="custom")this.sessionManager.appendCustomMessageEntry(event.message.customType,event.message.content,event.message.display,event.message.details);else if(event.message.role==="user"||event.message.role==="assistant"||event.message.role==="toolResult"){let entryId=this.sessionManager.appendMessage(event.message);event.message.role==="assistant"?(event.message.stopReason==="aborted"&&(this._currentRunAborted=!0),await this._dispatchModelStreamLifecycle(event.message,event.message.stopReason==="error"||event.message.stopReason==="aborted"?"error":"done","committed"),this._modelStreamState=void 0,await this._dispatchModelResponseLifecycle(event.message,entryId)):event.message.role==="toolResult"&&(await this._dispatchToolCommitLifecycle(event.message,entryId),await this._dispatchToolResultLifecycle(event.message,entryId))}if(event.message.role==="assistant"){this._lastAssistantMessage=event.message;let assistantMsg=event.message;assistantMsg.stopReason!=="error"&&assistantMsg.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1,this._overflowTrimStage=0),assistantMsg.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}event.type==="turn_end"&&this._flushPendingCustomMessages()};async _dispatchModelStreamLifecycle(message,eventName,phase){await dispatchModelStreamLifecycle(this._internal,message,eventName,phase)}_willRetryAfterAgentEnd(event,signal){return willRetryAfterAgentEnd(this._internal,event,signal)}_findLastAssistantMessage(){let messages=this.agent.state.messages;for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if(msg.role==="assistant")return msg}}async _emitLifecycleEvents(event){if(event.type==="agent_start")this._turnIndex=0,await dispatchAgentStartLifecycle(this._internal);else if(event.type==="agent_end")await dispatchAgentEndLifecycle(this._internal);else if(event.type==="turn_start")await dispatchTurnStartLifecycle(this._internal,this._turnIndex);else if(event.type==="turn_end"){this._turnIndex++;let turnMessage=event.message,outcome=turnMessage.role==="assistant"&&(turnMessage.stopReason==="aborted"||turnMessage.stopReason==="error")?turnMessage.stopReason:void 0;await dispatchTurnEndLifecycle(this._internal,this._turnIndex,this.agent.state.messages.length,outcome)}else event.type==="message_start"?await dispatchMessageStartLifecycle(this._internal,event.message.role):event.type==="message_end"?await dispatchMessageEndLifecycle(this._internal,event.message.role):event.type==="tool_execution_start"&&await dispatchToolExecutionStartLifecycle(this._internal,event.toolCallId,event.toolName)}subscribe(listener){return this._eventListeners.push(listener),()=>{let index3=this._eventListeners.indexOf(listener);index3!==-1&&this._eventListeners.splice(index3,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){return this._disposePromise?this._disposePromise:(this._disposePromise=(async()=>{let errors=[];this._beginContextTransitionFence(),this._bashEpoch+=1;for(let abort of[()=>this._abortActiveCapabilityCommand("session disposed"),()=>this.abortRetry(),()=>this.abortCompaction(),()=>this.abortBranchSummary(),()=>this.abortBash(),()=>this._agentTaskScopeAbortController.abort("session disposed"),()=>this.agent.abort()])try{await abort()}catch(error2){errors.push(error2)}await Promise.allSettled([this._activeContextTransition,...this._activeBashPromises,this.waitForIdle()].filter(operation=>operation!==void 0)),this._disconnectFromAgent(),this._eventListeners=[],await dispatchSessionEndLifecycle(this._internal);let disposals=[()=>this._disposeCapabilityPlugins(),()=>this._capabilityRuntime?.disposeAll(),()=>this._agentTaskAdapter?.dispose?.(),()=>this._interactionHost?.dispose?.(),()=>this._bootstrapToolsHandle?.dispose(),()=>this._bootstrapSkillsHandle?.dispose(),()=>this._bootstrapRetryHandle?.dispose(),()=>this._bootstrapCompactionHandle?.dispose(),()=>this._bootstrapOverflowHandle?.dispose(),()=>this._bootstrapBranchSummaryHandle?.dispose(),()=>this._bootstrapAgentLoopHandle?.dispose(),()=>this._bootstrapLifecycleHandle?.dispose()];for(let dispose of disposals)try{await dispose()}catch(error2){errors.push(error2)}if(this._capabilityRuntime?.revokeAllAPIs(),this._capabilityPlugins.clear(),this._inlineCapabilityPlugins.clear(),this._bootstrapToolsHandle=void 0,this._bootstrapSkillsHandle=void 0,this._bootstrapRetryHandle=void 0,this._bootstrapCompactionHandle=void 0,this._bootstrapOverflowHandle=void 0,this._bootstrapBranchSummaryHandle=void 0,this._bootstrapAgentLoopHandle=void 0,this._bootstrapLifecycleHandle=void 0,cleanupSessionResources(this.sessionId),errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,`Agent session disposal failed: ${this.sessionId}`)})(),this._disposePromise)}get state(){return this.agent.state}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return this.agent.state.systemPrompt}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(t=>t.name)}getCapabilityRuntime(){if(!this._capabilityRuntime)throw new Error("Capability runtime is not available");return this._capabilityRuntime}onOutputArtifactCommit(listener){return this._outputArtifactCommitListeners.add(listener),()=>{this._outputArtifactCommitListeners.delete(listener)}}get isDisposed(){return this._disposePromise!==void 0}getSessionAPI(){return{getSessionId:()=>this.sessionManager.getSessionId(),getRevision:()=>this.sessionManager.getRevision(),registerEntryProjection:projection=>this.sessionManager.registerEntryProjection(projection),getContextSnapshot:()=>({version:1,revision:this._contextRevision,value:detachedSessionSnapshot(this.agent.state.messages)}),commitContext:async request=>{let commit=this._contextCommitQueue.then(async()=>{if(request.signal?.aborted)throw new Error("Context commit cancelled");let currentRevision=this._contextRevision;if(request.operationId.trim()==="")throw new Error("Context commit operationId is required");if(request.expectedRevision!==currentRevision)throw new Error(`Context revision conflict: expected ${request.expectedRevision}, current ${currentRevision}`);if(!Array.isArray(request.value))throw new Error("Session context commit requires a message array");if(await this.replaceContext(request.value),request.signal?.aborted)throw new Error("Context commit cancelled");return{version:1,status:"committed",revision:this._contextRevision,value:detachedSessionSnapshot(this.agent.state.messages)}});return this._contextCommitQueue=commit.then(()=>{},()=>{}),commit},getMessages:()=>detachedSessionSnapshot(this.agent.state.messages),isIdle:()=>this.isIdle,prompt:text=>this.prompt(text),steer:text=>this.steer(text),queueFollowUp:text=>this.sendUserMessage(text,{deliverAs:"followUp"}),abort:()=>this.abort(),waitForIdle:()=>this.waitForIdle(),getActiveTools:()=>this.getActiveToolNames(),...this._capabilityMode==="readonly"?{}:{setActiveTools:toolNames=>this.setActiveToolsByName(toolNames)},compact:customInstructions=>this.compact(customInstructions),navigateTree:(targetId,options)=>this.navigateTree(targetId,options),appendEntry:(customType,data)=>{let entryId=this.sessionManager.appendCustomEntry(customType,data===void 0?void 0:detachedSessionSnapshot(data)),entry=this.sessionManager.getEntry(entryId);return entry&&(this._emit({type:"entry_appended",entry}),dispatchSessionEntryAppendedLifecycle(this._internal,entryId,entry.type)),entryId},setSessionName:name=>this.setSessionName(name),getSessionName:()=>this.sessionManager.getSessionName(),setLabel:(entryId,label)=>this.sessionManager.appendLabelChange(entryId,label),getLabel:entryId=>this.sessionManager.getLabel(entryId),getAllTools:()=>definitionSnapshot(this.getAllTools()),getCommands:()=>collectCommandInfos(this._internal),getModel:()=>this.model?detachedSnapshot(modelFactsView(this.model)):void 0,getScopedModels:()=>detachedSnapshot(this.scopedModels.map(entry=>({model:modelFactsView(entry.model),...entry.thinkingLevel===void 0?{}:{thinkingLevel:entry.thinkingLevel}}))),getThinkingLevel:()=>this.thinkingLevel,...this._capabilityMode==="readonly"?{}:{setThinkingLevel:level=>this.setThinkingLevel(level)},...this._capabilityMode==="readonly"?{}:{setModel:async modelId=>{let scoped=this.scopedModels.find(entry=>entry.model.id===modelId);return!scoped||!this._modelRuntime.hasConfiguredAuth(scoped.model.provider)?!1:(await this.setModel(scoped.model),!0)}},getSystemPrompt:()=>this.systemPrompt,getSystemPromptOptions:()=>detachedSnapshot(this._baseSystemPromptOptions),getContextUsage:()=>getContextUsage(this._internal),sendMessage:(message,options)=>this.sendCustomMessage(message,options),getBranchEntries:()=>detachedSessionSnapshot(this.sessionManager.getBranch().map(entry=>({id:entry.id,parentId:entry.parentId,timestamp:entry.timestamp,type:entry.type,...entry.type==="message"?{message:{role:entry.message.role,..."content"in entry.message?{content:entry.message.content}:{}}}:{},...entry.type==="custom"?{customType:entry.customType,data:entry.data}:{}}))),exportArtifact:request=>{if(request.format!=="jsonl")throw new Error(`Unsupported session export format: ${request.format}`);return createSessionJsonlArtifact(this.sessionManager)}}}getCapabilityPlugins(){let handles=Array.from(this._capabilityPlugins.values());for(let handle of[this._bootstrapToolsHandle,this._bootstrapSkillsHandle,this._bootstrapRetryHandle,this._bootstrapCompactionHandle,this._bootstrapOverflowHandle,this._bootstrapBranchSummaryHandle,this._bootstrapLifecycleHandle])handle&&handles.push(handle);return handles}get contextStrategyName(){return this._contextStrategyName}_requireContextStrategy(){return requireContextStrategy(this._internal)}_requireIdleContextOperation(operation){requireIdleContextOperation(this._internal,operation)}_beginContextTransitionFence(){beginContextTransitionFence(this._internal)}_isContextTransitionCurrent(epoch,allowReload){return isContextTransitionCurrent(this._internal,epoch,allowReload)}_assertContextTransitionCurrent(epoch,allowReload){assertContextTransitionCurrent(this._internal,epoch,allowReload)}_enqueueContextTransition(operation,options){return enqueueContextTransition(this._internal,operation,options)}_copyContextMessages(value,strategyName,direction){return copyContextMessages(value,strategyName,direction)}async _applyContextTransition(messages,reason="session_replace",signal,options){return applyContextTransition(this._internal,messages,reason,signal,options)}async _dispatchContextReplacedLifecycle(reason,strategyName){await dispatchContextReplacedLifecycle(this._internal,reason,strategyName)}async _dispatchModelResponseLifecycle(message,entryId){await dispatchModelResponseLifecycle(this._internal,message,entryId)}async _dispatchToolCommitLifecycle(message,entryId){await dispatchToolCommitLifecycle(this._internal,message,entryId)}async _dispatchToolResultLifecycle(message,entryId){await dispatchToolResultLifecycle(this._internal,message,entryId)}async _dispatchSessionReloadLifecycle(generation){await dispatchSessionReloadLifecycle(this._internal,generation)}async snapshotContext(){return snapshotContext(this._internal)}async restoreContext(snapshot2){return restoreContext(this._internal,snapshot2)}async replaceContext(context){return replaceContext(this._internal,context)}_restoreContextTransition(snapshot2,reason,options){return restoreContextTransition(this._internal,snapshot2,reason,options)}async _trackCapabilityPlugin(key,loaded,previousToolNames){try{this._validateCapabilitySkillConflicts()}catch(error2){throw await loaded.dispose(),error2}let disposed=!1,handle={manifest:loaded.manifest,api:loaded.api,ready:loaded.ready,dispose:async()=>{if(!disposed){disposed=!0,this._suspendToolRegistryHookRefresh=!0;try{await loaded.dispose()}finally{this._suspendToolRegistryHookRefresh=!1}this._capabilityPlugins.delete(key),this._inlineCapabilityPlugins.delete(key),this._isDisposingCapabilityPlugins||(this._syncCapabilityTools(),this._refreshToolRegistry({activeToolNames:this.getActiveToolNames()}))}}};this._capabilityPlugins.set(key,handle),this._syncCapabilityTools();let newToolNames=this._capabilityRuntime.listTools().filter(tool=>this._capabilityMode!=="readonly"||!tool.source.startsWith("agent-forge.builtin.")&&!tool.source.startsWith("agent-forge.plugin.")||tool.readonlySafe===!0).map(tool=>tool.name).filter(name=>!previousToolNames.has(name));return this._refreshToolRegistry({activeToolNames:[...this.getActiveToolNames(),...newToolNames]}),handle}async loadCapabilityPluginManifest(manifestPath,options){let runtime=this._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let resolvedManifestPath=resolve11(this._cwd,manifestPath);if(this._capabilityPlugins.has(resolvedManifestPath))throw new Error(`Capability plugin manifest is already loaded: ${resolvedManifestPath}`);let previousToolNames=new Set(runtime.listTools().map(tool=>tool.name)),loaded=await loadCapabilityPluginFromManifest(runtime,resolvedManifestPath,options);return this._trackCapabilityPlugin(resolvedManifestPath,loaded,previousToolNames)}async loadCapabilityPlugin(manifest,factory){let runtime=this._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let key=`inline:${manifest.id}`;if(this._capabilityPlugins.has(key))throw new Error(`Capability plugin is already loaded in this session: ${manifest.id}`);let previousToolNames=new Set(runtime.listTools().map(tool=>tool.name)),loaded=await loadCapabilityPlugin(runtime,manifest,factory);this._inlineCapabilityPlugins.set(key,{manifest,factory});try{return await this._trackCapabilityPlugin(key,loaded,previousToolNames)}catch(error2){throw this._inlineCapabilityPlugins.delete(key),error2}}getAllTools(){return getAllTools(this._internal)}getToolDefinition(name){return getToolDefinition(this._internal,name)}setActiveToolsByName(toolNames){setActiveToolsByName(this._internal,toolNames)}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get observabilityGetMetricsRef(){return this._observabilityGetMetricsRef}get sessionName(){return this.sessionManager.getSessionName()}getRevision(){return this.sessionManager.getRevision()}get scopedModels(){return getScopedModels(this._internal)}setScopedModels(scopedModels){setScopedModels(this._internal,scopedModels)}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(text){return normalizePromptSnippet(text)}_normalizePromptGuidelines(guidelines){return normalizePromptGuidelines(guidelines)}_rebuildSystemPrompt(toolNames){return rebuildSystemPrompt(this._internal,toolNames)}async _runAgentPrompt(messages){return runPromptLoop(this._internal,messages)}_handlePostAgentRun(){return postAgentRun(this._internal)}async _runInputHandlers(text,images,source){let gateChain=this._capabilityRuntime?.getLoopHookChain("beforeInput")??[],currentText=text;for(let link of gateChain){let result=await link({text:currentText,source});if(result){if(result.block===!0){let reason=typeof result.reason=="string"&&result.reason.trim()!==""?result.reason:void 0;throw await dispatchInputGateBlockedLifecycle(this._internal,{source,textLength:currentText.length,reason}),new Error(reason===void 0?"Input rejected by an input gate":`Input rejected by an input gate: ${reason}`)}"text"in result&&typeof result.text=="string"&&(currentText=result.text)}}return dispatchInputReceivedLifecycle(this._internal,{source,textLength:currentText.length}),{text:currentText,images}}async prompt(text,options){if(this._reloadInProgress)throw new Error("Session reload in progress; prompts are unavailable");let expandPromptTemplates=options?.expandPromptTemplates??!0,preflightResult=options?.preflightResult,messages;try{if(expandPromptTemplates&&text.startsWith("/")&&await this._tryExecuteExtensionCommand(text))return preflightResult?.(!0),{status:"done"};if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");let{text:currentText,images:currentImages}=await this._runInputHandlers(text,options?.images,options?.source??"interactive"),expandedText=currentText;if(expandPromptTemplates&&(expandedText=this._expandSkillCommand(expandedText),expandedText=expandPromptTemplate(expandedText,[...this.promptTemplates])),this.isStreaming){if(!options?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");return options.streamingBehavior==="followUp"?await this._queueFollowUp(expandedText,currentImages):await this._queueSteer(expandedText,currentImages),preflightResult?.(!0),{status:"done"}}if(this._flushPendingBashMessages(),this._flushPendingCustomMessages(),!this.model)throw new Error(formatNoModelSelectedMessage());if(!(this.agent.streamFunction!==streamSimple||this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0))throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(formatNoApiKeyFoundMessage(this.model.provider));let lastAssistant=this._findLastAssistantMessage();lastAssistant&&await this._checkCompaction(lastAssistant,!1),messages=[];let userContent=[{type:"text",text:expandedText}];currentImages&&userContent.push(...currentImages),messages.push({role:"user",content:userContent,timestamp:Date.now()});for(let msg of this._pendingNextTurnMessages)messages.push(msg);this._pendingNextTurnMessages=[],await dispatchBeforeAgentStartLifecycle(this._internal,(currentImages?.length??0)>0),this._systemPromptOverride=void 0,this.agent.state.systemPrompt=this._baseSystemPrompt;let capabilitySystemPrompt=await dispatchBeforeAgentStartV2Lifecycle(this._internal,this._baseSystemPrompt,this._baseSystemPromptOptions);capabilitySystemPrompt!==void 0&&(this._systemPromptOverride=capabilitySystemPrompt,this.agent.state.systemPrompt=capabilitySystemPrompt)}catch(error2){throw preflightResult?.(!1),error2}return messages?(preflightResult?.(!0),this._runAgentPrompt(messages)):{status:"done"}}async _tryExecuteExtensionCommand(text){let spaceIndex=text.indexOf(" "),commandName=spaceIndex===-1?text.slice(1):text.slice(1,spaceIndex),args=spaceIndex===-1?"":text.slice(spaceIndex+1),runtime=this._capabilityRuntime;if(runtime?.hasCommand(commandName)){let templateConflict=this.promptTemplates.some(template=>template.name===commandName),skillName=commandName.startsWith("skill:")?commandName.slice(6):void 0,skillConflict=skillName!==void 0&&this._getAvailableSkills().some(skill=>skill.name===skillName);if(templateConflict||skillConflict){let source2=templateConflict?"prompt template":"skill";throw new Error(`Command is registered by both CapabilityAPI and ${source2}: ${commandName}`)}}else return!1;let source=runtime.listCommands().find(({definition})=>definition.name===commandName)?.source??"unknown",abortController=new AbortController;this._commandAbortController=abortController;let commandExecution=(async()=>{let result=await runtime.invokeCommand(commandName,args,{signal:abortController.signal,cwd:this._cwd});result!==void 0&&this._emit({type:"capability_command_result",command:commandName,source,result})})();this._activeCapabilityCommand=commandExecution;try{await commandExecution}finally{this._commandAbortController===abortController&&(this._commandAbortController=void 0),this._activeCapabilityCommand===commandExecution&&(this._activeCapabilityCommand=void 0)}return!0}_expandSkillCommand(text){if(!text.startsWith("/skill:"))return text;let spaceIndex=text.indexOf(" "),skillName=spaceIndex===-1?text.slice(7):text.slice(7,spaceIndex),args=spaceIndex===-1?"":text.slice(spaceIndex+1).trim(),skill=this._getAvailableSkills().find(s=>s.name===skillName);if(!skill)return text;try{let content=readFileSync11(skill.filePath,"utf-8"),body=stripFrontmatter(content).trim(),skillBlock=`<skill name="${skill.name}" location="${skill.filePath}">
|
|
1050
|
+
`)}`}],details:{activated}}}}}function parseSkillBlock(text){let match2=text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return match2?{name:match2[1],location:match2[2],content:match2[3],userMessage:match2[4]?.trim()||void 0}:null}var SUITE_MISMATCH_SESSION_ENTRY_TYPE="suite_mismatch",AgentSession=class{agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionQueue=Promise.resolve();_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_overflowTrimStage=0;_microcompactCooldown=0;_branchSummaryAbortController=void 0;_branchSummaryPromise=void 0;_resolveBranchSummaryPromise=void 0;_retryAbortController=void 0;_policyDecisionAbortController=void 0;_retryAttempt=0;_commandAbortController=void 0;_agentTaskScopeAbortController=new AbortController;_activeCapabilityCommand;_activeCompactionPromise;_reloadInProgress=!1;_reloadGeneration=0;_contextEpoch=0;_contextTransitionAbortController=new AbortController;_activeContextTransition;_contextRevision=0;_contextCommitQueue=Promise.resolve();_bashAbortControllers=new Set;_activeBashPromises=new Set;_bashEpoch=0;_pendingBashMessages=[];_turnIndex=0;_resourceLoader;_customTools;_deferredToolPluginIds;_pendingAbortReason;_currentRunAborted=!1;_lastAbortReason;_baseToolDefinitions=new Map;_baseToolSources=new Map;_capabilityRuntime;_outputArtifactCommitListeners=new Set;_dispatchOutputArtifactCommit=artifact=>{for(let listener of[...this._outputArtifactCommitListeners])listener(artifact)};_bootstrapToolsHandle;_bootstrapSkillsHandle;_bootstrapRetryHandle;_bootstrapCompactionHandle;_bootstrapBranchSummaryHandle;_bootstrapOverflowHandle;_bootstrapAgentLoopHandle;_bootstrapLifecycleHandle;_capabilityPlugins=new Map;_inlineCapabilityPlugins=new Map;_isDisposingCapabilityPlugins=!1;_suspendToolRegistryHookRefresh=!1;_toolRegistryHookReady=!1;_disposePromise;_cwd;_initialActiveToolNames;_allowedToolNames;_excludedToolNames;_baseToolsOverride;_disabledBootstrapPlugins;_sessionStartEvent;_capabilityMode;_contextStrategyName;_retryPolicyName;_compactionPolicyName;_branchSummaryPolicyName;_overflowPolicyName;_runLoopStrategyName;_loopExecutor;_initialPrepareNextTurn;_agentTaskAdapter;_agentTaskResults;_agentSessionReader;_agentSessionLister;_agentComposition;_interactionHost;_modelRuntime;_modelStreamCounter=0;_modelStreamState;_turnCorrelationId;_turnCorrelationCounter=0;_toolRegistry=new Map;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPrompt="";_baseSystemPromptOptions;_systemPromptOverride;_orientationPrompt;_preferenceCard;_capabilitySkillsFilter;_hostLogger;_logRecordMirrorRef;_observabilityGetMetricsRef;_agentDir;_communication;_turnContext;_roleAssociations;_memoryStorage;_traceService;constructor(config){this.agent=config.agent,this.sessionManager=config.sessionManager,this._contextRevision=this.sessionManager.getRevision().sequence,this.settingsManager=config.settingsManager,this._scopedModels=config.scopedModels??[],this._resourceLoader=config.resourceLoader,this._customTools=config.customTools??[],this._deferredToolPluginIds=new Set(config.deferredToolPluginIds??[]),this._deferredToolPluginIds.size>0&&this._customTools.push(createToolSearchTool({listAllToolNames:()=>Array.from(this._toolRegistry.keys()),getToolInfo:name=>{let definition=this._toolDefinitions.get(name)?.definition;return definition?{name:definition.name,description:definition.description}:void 0},getActiveToolNames:()=>this.getActiveToolNames(),setActiveToolsByName:toolNames=>this.setActiveToolsByName(toolNames)})),this._cwd=config.cwd,this._modelRuntime=config.modelRuntime,this._initialActiveToolNames=config.initialActiveToolNames,this._allowedToolNames=config.allowedToolNames?new Set(config.allowedToolNames):void 0,this._excludedToolNames=config.excludedToolNames?new Set(config.excludedToolNames):void 0,this._baseToolsOverride=config.baseToolsOverride,this._disabledBootstrapPlugins=config.disabledBootstrapPlugins,this._sessionStartEvent=config.sessionStartEvent??{reason:"startup"},this._capabilityMode=config.capabilityMode??"full-control",this._contextStrategyName=config.contextStrategyName,this._retryPolicyName=config.retryPolicyName??DEFAULT_RETRY_POLICY_NAME,this._compactionPolicyName=config.compactionPolicyName??DEFAULT_COMPACTION_POLICY_NAME,this._branchSummaryPolicyName=config.branchSummaryPolicyName??DEFAULT_BRANCH_SUMMARY_POLICY_NAME,this._overflowPolicyName=config.overflowPolicyName??DEFAULT_OVERFLOW_POLICY_NAME,this._runLoopStrategyName=config.runLoopStrategyName??DEFAULT_RUN_LOOP_STRATEGY_NAME,this._agentTaskAdapter=config.agentTaskAdapter,this._agentTaskResults=config.agentTaskResults,this._agentSessionReader=config.agentSessionReader,this._agentSessionLister=config.agentSessionLister,this._agentComposition=config.agentComposition,this._interactionHost=config.interactionHost,this._orientationPrompt=config.orientationPrompt,this._preferenceCard=config.preferenceCard,this._capabilitySkillsFilter=config.capabilitySkillsFilter,this._hostLogger=config.hostLogger,this._logRecordMirrorRef=config.logRecordMirrorRef,this._observabilityGetMetricsRef=config.observabilityGetMetricsRef,this._agentDir=config.agentDir,this._communication=config.communication,this._turnContext=config.turnContext,this._roleAssociations=config.roleAssociations,this._memoryStorage=config.memoryStorage,this._traceService=config.traceService,this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._wireDefaultLoop()}getTurnCorrelationId(){return this._turnCorrelationId}dispatchAgentTaskSettled(facts){dispatchAgentTaskSettledLifecycle(this._internal,facts)}get modelRuntime(){return this._modelRuntime}get _internal(){return this}_wireDefaultLoop(){wireDefaultLoop(this._internal)}_createLoopWiring(){return createLoopWiring(this._internal)}_compactBeforeNextAssistantResponse(context,signal){return compactBeforeNextAssistantResponse(this._internal,context,signal)}_emit(event){for(let l3 of this._eventListeners)l3(event)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(resolve25=>{this._resolveIdleWait=resolve25})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;let resolve25=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,resolve25()}async _emitAgentSettled(){this._isAgentRunActive=!1;try{this._emit({type:"agent_settled"}),await dispatchAgentSettledLifecycle(this._internal)}finally{this._resolveIdleWaitIfIdle()}}_lastAssistantMessage=void 0;_pendingRetryDecision=void 0;_handleAgentEvent=async event=>{if(event.type==="message_start"&&event.message.role==="assistant"&&(this._modelStreamState={streamId:`model-stream:${++this._modelStreamCounter}`,sequence:0},await this._dispatchModelStreamLifecycle(event.message,"start","raw")),event.type==="message_start"&&event.message.role==="user"){this._overflowRecoveryAttempted=!1,this._overflowTrimStage=0;let messageText=contentText(event.message.content,"");if(messageText){let steeringIndex=this._steeringMessages.indexOf(messageText);if(steeringIndex!==-1)this._steeringMessages.splice(steeringIndex,1),this._emitQueueUpdate();else{let followUpIndex=this._followUpMessages.indexOf(messageText);followUpIndex!==-1&&(this._followUpMessages.splice(followUpIndex,1),this._emitQueueUpdate())}}}if(await this._emitLifecycleEvents(event),event.type==="message_update"&&event.message.role==="assistant"&&await this._dispatchModelStreamLifecycle(event.message,event.assistantMessageEvent.type,"candidate"),this._emit(event.type==="agent_end"?{...event,willRetry:await this._willRetryAfterAgentEnd(event,this._policyDecisionAbortController?.signal)}:event),event.type==="message_end"){if(event.message.role==="custom")this.sessionManager.appendCustomMessageEntry(event.message.customType,event.message.content,event.message.display,event.message.details);else if(event.message.role==="user"||event.message.role==="assistant"||event.message.role==="toolResult"){let entryId=this.sessionManager.appendMessage(event.message);event.message.role==="assistant"?(event.message.stopReason==="aborted"&&(this._currentRunAborted=!0),await this._dispatchModelStreamLifecycle(event.message,event.message.stopReason==="error"||event.message.stopReason==="aborted"?"error":"done","committed"),this._modelStreamState=void 0,await this._dispatchModelResponseLifecycle(event.message,entryId)):event.message.role==="toolResult"&&(await this._dispatchToolCommitLifecycle(event.message,entryId),await this._dispatchToolResultLifecycle(event.message,entryId))}if(event.message.role==="assistant"){this._lastAssistantMessage=event.message;let assistantMsg=event.message;assistantMsg.stopReason!=="error"&&assistantMsg.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1,this._overflowTrimStage=0),this._microcompactCooldown>0&&(this._microcompactCooldown-=1),assistantMsg.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}event.type==="turn_end"&&this._flushPendingCustomMessages()};async _dispatchModelStreamLifecycle(message,eventName,phase){await dispatchModelStreamLifecycle(this._internal,message,eventName,phase)}_willRetryAfterAgentEnd(event,signal){return willRetryAfterAgentEnd(this._internal,event,signal)}_findLastAssistantMessage(){let messages=this.agent.state.messages;for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if(msg.role==="assistant")return msg}}async _emitLifecycleEvents(event){if(event.type==="agent_start")this._turnIndex=0,await dispatchAgentStartLifecycle(this._internal);else if(event.type==="agent_end")await dispatchAgentEndLifecycle(this._internal);else if(event.type==="turn_start")await dispatchTurnStartLifecycle(this._internal,this._turnIndex);else if(event.type==="turn_end"){this._turnIndex++;let turnMessage=event.message,outcome=turnMessage.role==="assistant"&&(turnMessage.stopReason==="aborted"||turnMessage.stopReason==="error")?turnMessage.stopReason:void 0;await dispatchTurnEndLifecycle(this._internal,this._turnIndex,this.agent.state.messages.length,outcome)}else event.type==="message_start"?await dispatchMessageStartLifecycle(this._internal,event.message.role):event.type==="message_end"?await dispatchMessageEndLifecycle(this._internal,event.message.role):event.type==="tool_execution_start"&&await dispatchToolExecutionStartLifecycle(this._internal,event.toolCallId,event.toolName)}subscribe(listener){return this._eventListeners.push(listener),()=>{let index3=this._eventListeners.indexOf(listener);index3!==-1&&this._eventListeners.splice(index3,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){return this._disposePromise?this._disposePromise:(this._disposePromise=(async()=>{let errors=[];this._beginContextTransitionFence(),this._bashEpoch+=1;for(let abort of[()=>this._abortActiveCapabilityCommand("session disposed"),()=>this.abortRetry(),()=>this.abortCompaction(),()=>this.abortBranchSummary(),()=>this.abortBash(),()=>this._agentTaskScopeAbortController.abort("session disposed"),()=>this.agent.abort()])try{await abort()}catch(error2){errors.push(error2)}await Promise.allSettled([this._activeContextTransition,...this._activeBashPromises,this.waitForIdle()].filter(operation=>operation!==void 0)),this._disconnectFromAgent(),this._eventListeners=[],await dispatchSessionEndLifecycle(this._internal);let disposals=[()=>this._disposeCapabilityPlugins(),()=>this._capabilityRuntime?.disposeAll(),()=>this._agentTaskAdapter?.dispose?.(),()=>this._interactionHost?.dispose?.(),()=>this._bootstrapToolsHandle?.dispose(),()=>this._bootstrapSkillsHandle?.dispose(),()=>this._bootstrapRetryHandle?.dispose(),()=>this._bootstrapCompactionHandle?.dispose(),()=>this._bootstrapOverflowHandle?.dispose(),()=>this._bootstrapBranchSummaryHandle?.dispose(),()=>this._bootstrapAgentLoopHandle?.dispose(),()=>this._bootstrapLifecycleHandle?.dispose()];for(let dispose of disposals)try{await dispose()}catch(error2){errors.push(error2)}if(this._capabilityRuntime?.revokeAllAPIs(),this._capabilityPlugins.clear(),this._inlineCapabilityPlugins.clear(),this._bootstrapToolsHandle=void 0,this._bootstrapSkillsHandle=void 0,this._bootstrapRetryHandle=void 0,this._bootstrapCompactionHandle=void 0,this._bootstrapOverflowHandle=void 0,this._bootstrapBranchSummaryHandle=void 0,this._bootstrapAgentLoopHandle=void 0,this._bootstrapLifecycleHandle=void 0,cleanupSessionResources(this.sessionId),errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,`Agent session disposal failed: ${this.sessionId}`)})(),this._disposePromise)}get state(){return this.agent.state}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return this.agent.state.systemPrompt}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(t=>t.name)}getCapabilityRuntime(){if(!this._capabilityRuntime)throw new Error("Capability runtime is not available");return this._capabilityRuntime}onOutputArtifactCommit(listener){return this._outputArtifactCommitListeners.add(listener),()=>{this._outputArtifactCommitListeners.delete(listener)}}get isDisposed(){return this._disposePromise!==void 0}getSessionAPI(){return{getSessionId:()=>this.sessionManager.getSessionId(),getRevision:()=>this.sessionManager.getRevision(),registerEntryProjection:projection=>this.sessionManager.registerEntryProjection(projection),getContextSnapshot:()=>({version:1,revision:this._contextRevision,value:detachedSessionSnapshot(this.agent.state.messages)}),commitContext:async request=>{let commit=this._contextCommitQueue.then(async()=>{if(request.signal?.aborted)throw new Error("Context commit cancelled");let currentRevision=this._contextRevision;if(request.operationId.trim()==="")throw new Error("Context commit operationId is required");if(request.expectedRevision!==currentRevision)throw new Error(`Context revision conflict: expected ${request.expectedRevision}, current ${currentRevision}`);if(!Array.isArray(request.value))throw new Error("Session context commit requires a message array");if(await this.replaceContext(request.value),request.signal?.aborted)throw new Error("Context commit cancelled");return{version:1,status:"committed",revision:this._contextRevision,value:detachedSessionSnapshot(this.agent.state.messages)}});return this._contextCommitQueue=commit.then(()=>{},()=>{}),commit},getMessages:()=>detachedSessionSnapshot(this.agent.state.messages),isIdle:()=>this.isIdle,prompt:text=>this.prompt(text),steer:text=>this.steer(text),queueFollowUp:text=>this.sendUserMessage(text,{deliverAs:"followUp"}),abort:()=>this.abort(),waitForIdle:()=>this.waitForIdle(),getActiveTools:()=>this.getActiveToolNames(),...this._capabilityMode==="readonly"?{}:{setActiveTools:toolNames=>this.setActiveToolsByName(toolNames)},compact:customInstructions=>this.compact(customInstructions),navigateTree:(targetId,options)=>this.navigateTree(targetId,options),appendEntry:(customType,data)=>{let entryId=this.sessionManager.appendCustomEntry(customType,data===void 0?void 0:detachedSessionSnapshot(data)),entry=this.sessionManager.getEntry(entryId);return entry&&(this._emit({type:"entry_appended",entry}),dispatchSessionEntryAppendedLifecycle(this._internal,entryId,entry.type)),entryId},setSessionName:name=>this.setSessionName(name),getSessionName:()=>this.sessionManager.getSessionName(),setLabel:(entryId,label)=>this.sessionManager.appendLabelChange(entryId,label),getLabel:entryId=>this.sessionManager.getLabel(entryId),getAllTools:()=>definitionSnapshot(this.getAllTools()),getCommands:()=>collectCommandInfos(this._internal),getModel:()=>this.model?detachedSnapshot(modelFactsView(this.model)):void 0,getScopedModels:()=>detachedSnapshot(this.scopedModels.map(entry=>({model:modelFactsView(entry.model),...entry.thinkingLevel===void 0?{}:{thinkingLevel:entry.thinkingLevel}}))),getThinkingLevel:()=>this.thinkingLevel,...this._capabilityMode==="readonly"?{}:{setThinkingLevel:level=>this.setThinkingLevel(level)},...this._capabilityMode==="readonly"?{}:{setModel:async modelId=>{let scoped=this.scopedModels.find(entry=>entry.model.id===modelId);return!scoped||!this._modelRuntime.hasConfiguredAuth(scoped.model.provider)?!1:(await this.setModel(scoped.model),!0)}},getSystemPrompt:()=>this.systemPrompt,getSystemPromptOptions:()=>detachedSnapshot(this._baseSystemPromptOptions),getContextUsage:()=>getContextUsage(this._internal),sendMessage:(message,options)=>this.sendCustomMessage(message,options),getBranchEntries:()=>detachedSessionSnapshot(this.sessionManager.getBranch().map(entry=>({id:entry.id,parentId:entry.parentId,timestamp:entry.timestamp,type:entry.type,...entry.type==="message"?{message:{role:entry.message.role,..."content"in entry.message?{content:entry.message.content}:{}}}:{},...entry.type==="custom"?{customType:entry.customType,data:entry.data}:{}}))),exportArtifact:request=>{if(request.format!=="jsonl")throw new Error(`Unsupported session export format: ${request.format}`);return createSessionJsonlArtifact(this.sessionManager)}}}getCapabilityPlugins(){let handles=Array.from(this._capabilityPlugins.values());for(let handle of[this._bootstrapToolsHandle,this._bootstrapSkillsHandle,this._bootstrapRetryHandle,this._bootstrapCompactionHandle,this._bootstrapOverflowHandle,this._bootstrapBranchSummaryHandle,this._bootstrapLifecycleHandle])handle&&handles.push(handle);return handles}get contextStrategyName(){return this._contextStrategyName}_requireContextStrategy(){return requireContextStrategy(this._internal)}_requireIdleContextOperation(operation){requireIdleContextOperation(this._internal,operation)}_beginContextTransitionFence(){beginContextTransitionFence(this._internal)}_isContextTransitionCurrent(epoch,allowReload){return isContextTransitionCurrent(this._internal,epoch,allowReload)}_assertContextTransitionCurrent(epoch,allowReload){assertContextTransitionCurrent(this._internal,epoch,allowReload)}_enqueueContextTransition(operation,options){return enqueueContextTransition(this._internal,operation,options)}_copyContextMessages(value,strategyName,direction){return copyContextMessages(value,strategyName,direction)}async _applyContextTransition(messages,reason="session_replace",signal,options){return applyContextTransition(this._internal,messages,reason,signal,options)}async _dispatchContextReplacedLifecycle(reason,strategyName){await dispatchContextReplacedLifecycle(this._internal,reason,strategyName)}async _dispatchModelResponseLifecycle(message,entryId){await dispatchModelResponseLifecycle(this._internal,message,entryId)}async _dispatchToolCommitLifecycle(message,entryId){await dispatchToolCommitLifecycle(this._internal,message,entryId)}async _dispatchToolResultLifecycle(message,entryId){await dispatchToolResultLifecycle(this._internal,message,entryId)}async _dispatchSessionReloadLifecycle(generation){await dispatchSessionReloadLifecycle(this._internal,generation)}async snapshotContext(){return snapshotContext(this._internal)}async restoreContext(snapshot2){return restoreContext(this._internal,snapshot2)}async replaceContext(context){return replaceContext(this._internal,context)}_restoreContextTransition(snapshot2,reason,options){return restoreContextTransition(this._internal,snapshot2,reason,options)}async _trackCapabilityPlugin(key,loaded,previousToolNames){try{this._validateCapabilitySkillConflicts()}catch(error2){throw await loaded.dispose(),error2}let disposed=!1,handle={manifest:loaded.manifest,api:loaded.api,ready:loaded.ready,dispose:async()=>{if(!disposed){disposed=!0,this._suspendToolRegistryHookRefresh=!0;try{await loaded.dispose()}finally{this._suspendToolRegistryHookRefresh=!1}this._capabilityPlugins.delete(key),this._inlineCapabilityPlugins.delete(key),this._isDisposingCapabilityPlugins||(this._syncCapabilityTools(),this._refreshToolRegistry({activeToolNames:this.getActiveToolNames()}))}}};this._capabilityPlugins.set(key,handle),this._syncCapabilityTools();let newToolNames=this._capabilityRuntime.listTools().filter(tool=>this._capabilityMode!=="readonly"||!tool.source.startsWith("agent-forge.builtin.")&&!tool.source.startsWith("agent-forge.plugin.")||tool.readonlySafe===!0).map(tool=>tool.name).filter(name=>!previousToolNames.has(name));return this._refreshToolRegistry({activeToolNames:[...this.getActiveToolNames(),...newToolNames]}),handle}async loadCapabilityPluginManifest(manifestPath,options){let runtime=this._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let resolvedManifestPath=resolve11(this._cwd,manifestPath);if(this._capabilityPlugins.has(resolvedManifestPath))throw new Error(`Capability plugin manifest is already loaded: ${resolvedManifestPath}`);let previousToolNames=new Set(runtime.listTools().map(tool=>tool.name)),loaded=await loadCapabilityPluginFromManifest(runtime,resolvedManifestPath,options);return this._trackCapabilityPlugin(resolvedManifestPath,loaded,previousToolNames)}async loadCapabilityPlugin(manifest,factory){let runtime=this._capabilityRuntime;if(!runtime)throw new Error("Capability runtime is not available");let key=`inline:${manifest.id}`;if(this._capabilityPlugins.has(key))throw new Error(`Capability plugin is already loaded in this session: ${manifest.id}`);let previousToolNames=new Set(runtime.listTools().map(tool=>tool.name)),loaded=await loadCapabilityPlugin(runtime,manifest,factory);this._inlineCapabilityPlugins.set(key,{manifest,factory});try{return await this._trackCapabilityPlugin(key,loaded,previousToolNames)}catch(error2){throw this._inlineCapabilityPlugins.delete(key),error2}}getAllTools(){return getAllTools(this._internal)}getToolDefinition(name){return getToolDefinition(this._internal,name)}setActiveToolsByName(toolNames){setActiveToolsByName(this._internal,toolNames)}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get observabilityGetMetricsRef(){return this._observabilityGetMetricsRef}get sessionName(){return this.sessionManager.getSessionName()}getRevision(){return this.sessionManager.getRevision()}get scopedModels(){return getScopedModels(this._internal)}setScopedModels(scopedModels){setScopedModels(this._internal,scopedModels)}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(text){return normalizePromptSnippet(text)}_normalizePromptGuidelines(guidelines){return normalizePromptGuidelines(guidelines)}_rebuildSystemPrompt(toolNames){return rebuildSystemPrompt(this._internal,toolNames)}async _runAgentPrompt(messages){return runPromptLoop(this._internal,messages)}_handlePostAgentRun(){return postAgentRun(this._internal)}async _runInputHandlers(text,images,source){let gateChain=this._capabilityRuntime?.getLoopHookChain("beforeInput")??[],currentText=text;for(let link of gateChain){let result=await link({text:currentText,source});if(result){if(result.block===!0){let reason=typeof result.reason=="string"&&result.reason.trim()!==""?result.reason:void 0;throw await dispatchInputGateBlockedLifecycle(this._internal,{source,textLength:currentText.length,reason}),new Error(reason===void 0?"Input rejected by an input gate":`Input rejected by an input gate: ${reason}`)}"text"in result&&typeof result.text=="string"&&(currentText=result.text)}}return dispatchInputReceivedLifecycle(this._internal,{source,textLength:currentText.length}),{text:currentText,images}}async prompt(text,options){if(this._reloadInProgress)throw new Error("Session reload in progress; prompts are unavailable");let expandPromptTemplates=options?.expandPromptTemplates??!0,preflightResult=options?.preflightResult,messages;try{if(expandPromptTemplates&&text.startsWith("/")&&await this._tryExecuteExtensionCommand(text))return preflightResult?.(!0),{status:"done"};if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");let{text:currentText,images:currentImages}=await this._runInputHandlers(text,options?.images,options?.source??"interactive"),expandedText=currentText;if(expandPromptTemplates&&(expandedText=this._expandSkillCommand(expandedText),expandedText=expandPromptTemplate(expandedText,[...this.promptTemplates])),this.isStreaming){if(!options?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");return options.streamingBehavior==="followUp"?await this._queueFollowUp(expandedText,currentImages):await this._queueSteer(expandedText,currentImages),preflightResult?.(!0),{status:"done"}}if(this._flushPendingBashMessages(),this._flushPendingCustomMessages(),!this.model)throw new Error(formatNoModelSelectedMessage());if(!(this.agent.streamFunction!==streamSimple||this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0))throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(formatNoApiKeyFoundMessage(this.model.provider));let lastAssistant=this._findLastAssistantMessage();lastAssistant&&await this._checkCompaction(lastAssistant,!1),messages=[];let userContent=[{type:"text",text:expandedText}];currentImages&&userContent.push(...currentImages),messages.push({role:"user",content:userContent,timestamp:Date.now()});for(let msg of this._pendingNextTurnMessages)messages.push(msg);this._pendingNextTurnMessages=[],await dispatchBeforeAgentStartLifecycle(this._internal,(currentImages?.length??0)>0),this._systemPromptOverride=void 0,this.agent.state.systemPrompt=this._baseSystemPrompt;let capabilitySystemPrompt=await dispatchBeforeAgentStartV2Lifecycle(this._internal,this._baseSystemPrompt,this._baseSystemPromptOptions);capabilitySystemPrompt!==void 0&&(this._systemPromptOverride=capabilitySystemPrompt,this.agent.state.systemPrompt=capabilitySystemPrompt)}catch(error2){throw preflightResult?.(!1),error2}return messages?(preflightResult?.(!0),this._runAgentPrompt(messages)):{status:"done"}}async _tryExecuteExtensionCommand(text){let spaceIndex=text.indexOf(" "),commandName=spaceIndex===-1?text.slice(1):text.slice(1,spaceIndex),args=spaceIndex===-1?"":text.slice(spaceIndex+1),runtime=this._capabilityRuntime;if(runtime?.hasCommand(commandName)){let templateConflict=this.promptTemplates.some(template=>template.name===commandName),skillName=commandName.startsWith("skill:")?commandName.slice(6):void 0,skillConflict=skillName!==void 0&&this._getAvailableSkills().some(skill=>skill.name===skillName);if(templateConflict||skillConflict){let source2=templateConflict?"prompt template":"skill";throw new Error(`Command is registered by both CapabilityAPI and ${source2}: ${commandName}`)}}else return!1;let source=runtime.listCommands().find(({definition})=>definition.name===commandName)?.source??"unknown",abortController=new AbortController;this._commandAbortController=abortController;let commandExecution=(async()=>{let result=await runtime.invokeCommand(commandName,args,{signal:abortController.signal,cwd:this._cwd});result!==void 0&&this._emit({type:"capability_command_result",command:commandName,source,result})})();this._activeCapabilityCommand=commandExecution;try{await commandExecution}finally{this._commandAbortController===abortController&&(this._commandAbortController=void 0),this._activeCapabilityCommand===commandExecution&&(this._activeCapabilityCommand=void 0)}return!0}_expandSkillCommand(text){if(!text.startsWith("/skill:"))return text;let spaceIndex=text.indexOf(" "),skillName=spaceIndex===-1?text.slice(7):text.slice(7,spaceIndex),args=spaceIndex===-1?"":text.slice(spaceIndex+1).trim(),skill=this._getAvailableSkills().find(s=>s.name===skillName);if(!skill)return text;try{let content=readFileSync11(skill.filePath,"utf-8"),body=stripFrontmatter(content).trim(),skillBlock=`<skill name="${skill.name}" location="${skill.filePath}">
|
|
1051
1051
|
References are relative to ${skill.baseDir}.
|
|
1052
1052
|
|
|
1053
1053
|
${body}
|
|
@@ -1056,7 +1056,7 @@ ${body}
|
|
|
1056
1056
|
${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(`
|
|
1057
1057
|
`),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,`*
|
|
1058
1058
|
!.gitignore
|
|
1059
|
-
`,"utf-8")}function getInstalledNpmVersion(installedPath){let packageJsonPath=join38(installedPath,"package.json");if(existsSync13(packageJsonPath))try{let content=readFileSync12(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}function installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver2.satisfies)(installedVersion,source.range):!0:!1}function hasMissingGitDependencies(targetDir){let packageJsonPath=join38(targetDir,"package.json");if(!existsSync13(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync12(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve12(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve12(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep8}`)?!existsSync13(dependencyPath):!1})}catch{return!1}}function getGitUpdateMarkerPath(targetDir){return join38(dirname20(targetDir),`.${basename10(targetDir)}.agent-forge-update-incomplete`)}function pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve12(installRoot),current=dirname20(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync13(current)){current=dirname20(current);continue}if(readdirSync11(current).length>0)break;try{rmSync3(current,{recursive:!0,force:!0})}catch{break}current=dirname20(current)}}import{readFileSync as readFileSync13}from"node:fs";function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync13("/proc/self/environ","utf-8"),env2={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env2[entry.slice(0,idx)]=entry.slice(idx+1))}return env2}catch{return process.env}}function isOfflineModeEnabled2(){let value=process.env.AGENT_FORGE_OFFLINE;return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}async function runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index3=nextIndex;if(nextIndex+=1,index3>=tasks.length)return;results[index3]=await tasks[index3]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}import{existsSync as existsSync15,statSync as statSync12}from"node:fs";import{dirname as dirname22,join as join41,resolve as resolve14}from"node:path";var import_ignore3=__toESM(require_ignore(),1);import{existsSync as existsSync14,globSync,readdirSync as readdirSync12,readFileSync as readFileSync14,statSync as statSync11}from"node:fs";import{basename as basename11,dirname as dirname21,join as join39,relative as relative6,resolve as resolve13,sep as sep9}from"node:path";var RESOURCE_TYPES=["skills","prompts","themes"],FILE_PATTERNS={skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath3(p){return p.split(sep9).join("/")}function prefixIgnorePattern2(line,prefix){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative6(rootDir,dir),prefix=relativeDir?`${toPosixPath3(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join39(dir,filename);if(existsSync14(ignorePath))try{let patterns=readFileSync14(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve13(root,match2)).filter(path15=>relative6(root,path15).split(sep9).every(segment2=>segment2===".."||!segment2.startsWith("."))).sort((a,b2)=>a<b2?-1:a>b2?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync14(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync12(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync14(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!ig.ignores(relPath)&&(mode==="project"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}isDir&&(ig.ignores(`${relPath}/`)||entries.push(...collectSkillEntries(fullPath,mode,ig,root)))}}catch{}return entries}function collectAutoSkillEntries(dir,mode){return collectSkillEntries(dir,mode)}function findGitRepoRoot(startDir){let dir=resolve13(startDir);for(;;){if(existsSync14(join39(dir,".git")))return dir;let parent=dirname21(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve13(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join39(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname21(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function collectResourceFiles(dir,resourceType){return resourceType==="skills"?collectSkillEntries(dir,"project"):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentName=isSkillFile?basename11(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath3(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath3(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var import_semver3=__toESM(require_semver2(),1);import{homedir as homedir7}from"node:os";import{join as join40,relative as relative7}from"node:path";var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path15="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path15=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path15=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path15=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path15,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}function isExactNpmVersion(version){return(0,import_semver3.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver3.validRange)(version)??void 0:void 0}function getHomeDir(){return process.env.HOME||homedir7()}function getBaseDirForScope(ctx,scope){return scope==="project"?join40(ctx.cwd,CONFIG_DIR_NAME):scope==="user"?ctx.agentDir:ctx.cwd}function resolvePath3(ctx,input){return resolvePath(input,ctx.cwd,{homeDir:getHomeDir(),trim:!0})}function resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}function parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}function parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}function getPackageSourceString(pkg2){return typeof pkg2=="string"?pkg2:pkg2.source}function getSourceMatchKeyForInput(ctx,source){let parsed=parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${resolvePath3(ctx,parsed.path)}`}function getSourceMatchKeyForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}function buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}function findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg2 of configuredPackages){let sourceStr=getPackageSourceString(pkg2),parsed=parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}function normalizePackageSourceForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type!=="local")return source;let baseDir=getBaseDirForScope(ctx,scope),resolved=resolvePath3(ctx,parsed.path);return relative7(baseDir,resolved)||"."}function getPackageIdentity(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}return`local:${resolvePath3(ctx,parsed.path)}`}function dedupePackages(ctx,packages){let result=[],seen=new Map;for(let entry of packages){let identity=getPackageIdentity(ctx,getPackageSourceString(entry.pkg),entry.scope),index3=seen.get(identity);if(index3===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index3];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index3]=entry)}return result}import{readFileSync as readFileSync15}from"node:fs";var RESOURCE_FIELDS=["skills","prompts","themes"];function isObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg2=JSON.parse(stripBom(readFileSync15(packageJsonPath,"utf-8")));if(!isObject4(pkg2)||!isObject4(pkg2.pi))return null;let manifest={};for(let field2 of RESOURCE_FIELDS){let entries=pkg2.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}function resourcePrecedenceRank(m2){return m2.origin==="package"?4:(m2.scope==="project"?0:2)+(m2.source==="local"?0:1)}function collectPackageResources(packageRoot,accumulator,filter2,metadata){if(filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=getTargetMap(accumulator,resourceType);filter2.autoload===!1?applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}let manifest=readPiManifest(join41(packageRoot,"package.json"));if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];addManifestEntries(entries,packageRoot,resourceType,getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}function collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries){addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(target,f,metadata,!0)}}function applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=collectManifestFiles(packageRoot,resourceType);if(userPatterns.length===0){for(let f of allFiles)addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);addResource(target,f,metadata,enabled)}}function applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=collectManifestFiles(packageRoot,resourceType),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)addResource(target,filePath,metadata,enabled)}function collectManifestFiles(packageRoot,resourceType){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=collectFilesFromManifestEntries(entries,packageRoot,resourceType),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join41(packageRoot,resourceType);if(!existsSync15(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType);return{allFiles,enabledByManifest:new Set(allFiles)}}function addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=collectFilesFromManifestEntries(entries,root,resourceType),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&addResource(target,f,metadata,!0)}function collectFilesFromManifestEntries(entries,root,resourceType){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve14(root,entry)]);return collectFilesFromPaths(resolved,resourceType)}function resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>resolvePathFromBase(p,baseDir)),allFiles=collectFilesFromPaths(resolvedPlain,resourceType),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)addResource(target,f,metadata,enabledPaths.has(f))}function addAutoDiscoveredResources(cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[]},projectOverrides={skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[]},userDirs={skills:join41(globalBaseDir,"skills"),prompts:join41(globalBaseDir,"prompts"),themes:join41(globalBaseDir,"themes")},projectDirs={skills:join41(projectBaseDir,"skills"),prompts:join41(projectBaseDir,"prompts"),themes:join41(projectBaseDir,"themes")},userAgentsSkillsDir=join41(getHomeDir(),".agents","skills"),projectAgentsSkillDirs=collectAncestorAgentsSkillDirs(cwd).filter(dir=>resolve14(dir)!==resolve14(userAgentsSkillsDir)),addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=getTargetMap(accumulator,resourceType);for(let path15 of paths){let enabled=isEnabledByOverrides(path15,overrides,baseDir);addResource(target,path15,metadata,enabled)}};addResources("skills",collectAutoSkillEntries(projectDirs.skills,"project"),projectMetadata,projectOverrides.skills,projectBaseDir);for(let agentsSkillsDir of projectAgentsSkillDirs){let agentsBaseDir=dirname22(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addResources("skills",collectAutoSkillEntries(agentsSkillsDir,"agents"),agentsMetadata,projectOverrides.skills,agentsBaseDir)}addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("skills",collectAutoSkillEntries(userDirs.skills,"project"),userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname22(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addResources("skills",collectAutoSkillEntries(userAgentsSkillsDir,"agents"),userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir)}function collectFilesFromPaths(paths,resourceType){let files=[];for(let p of paths)if(existsSync15(p))try{let stats=statSync12(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType))}catch{}return files}function getTargetMap(accumulator,resourceType){switch(resourceType){case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;default:throw new Error(`Unknown resource type: ${resourceType}`)}}function addResource(map,path15,metadata,enabled){path15&&(map.has(path15)||map.set(path15,{metadata,enabled}))}function createAccumulator(){return{skills:new Map,prompts:new Map,themes:new Map}}function toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path15,{metadata,enabled}])=>({path:path15,enabled,metadata}));resolved.sort((a,b2)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b2.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes)}}var NETWORK_TIMEOUT_MS2=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4,DefaultPackageManager=class{cwd;agentDir;settingsManager;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}get context(){return{cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path15=this.getNpmInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="git"){let path15=this.getGitInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path15=this.resolvePathFromBase(parsed.path,baseDir);return existsSync16(path15)?path15:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);throw this.emitProgress({type:"error",action,source,message:errorMessage2}),error2}}async resolve(onMissing){let accumulator=createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join42(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}return addAutoDiscoveredResources(this.cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),toResolvedPaths(accumulator)}async resolveSourceResources(sources,options){let accumulator=createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg2 of globalSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg2 of projectSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync16(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg2 of globalSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg2 of projectSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled2()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=getManagedNpmInstallPath(this.context,source,scope),installedVersion=existsSync16(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled2())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync16(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync16(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg:pkg2,scope}of sources){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source,filter2=typeof pkg2=="object"?pkg2:void 0,deltaBase=this.findAutoloadDeltaBase(pkg2,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope),resolvedLocal=this.resolvePathFromBase(parsed.path,baseDir);if(existsSync16(resolvedLocal))try{statSync13(resolvedLocal).isDirectory()&&(metadata.baseDir=resolvedLocal,collectPackageResources(resolvedLocal,accumulator,filter2,metadata))}catch{}continue}let installMissing=async()=>{if(isOfflineModeEnabled2())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync16(installedPath)||!await installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync16(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled2()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg2,scope,sources){if(scope!=="project"||typeof pkg2!="object"||pkg2.autoload!==!1)return;let identity=this.getPackageIdentity(pkg2.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}parseSource(source){return parseSource(source)}getBaseDirForScope(scope){return getBaseDirForScope(this.context,scope)}resolvePath(input){return resolvePath3(this.context,input)}resolvePathFromBase(input,baseDir){return resolvePathFromBase(input,baseDir)}getPackageSourceString(pkg2){return getPackageSourceString(pkg2)}getSourceMatchKeyForInput(source){return getSourceMatchKeyForInput(this.context,source)}getSourceMatchKeyForSettings(source,scope){return getSourceMatchKeyForSettings(this.context,source,scope)}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){return normalizePackageSourceForSettings(this.context,source,scope)}getPackageIdentity(source,scope){return getPackageIdentity(this.context,source,scope)}dedupePackages(packages){return dedupePackages(this.context,packages)}buildNoMatchingPackageMessage(source,configuredPackages){return buildNoMatchingPackageMessage(source,configuredPackages)}getNpmCommand(){return getNpmCommand(this.context)}getInstalledNpmVersion(installedPath){return getInstalledNpmVersion(installedPath)}getGitInstallPath(source,scope){return getGitInstallPath(this.context,source,scope)}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled2())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}catch{return!1}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver4.maxSatisfying)(versions,range2):[...versions].sort(import_semver4.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled2())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2,env:{GIT_TERMINAL_PROMPT:"0"}})}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(getPackageManagerName(this.context)==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join42(dirname23(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(getPackageManagerName(this.context)!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path15=entry.dependencies?.[packageName]?.path;if(path15)return path15}}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join42(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=getManagedNpmInstallPath(this.context,source,scope);if(scope!=="user"||existsSync16(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync16(legacyPath)?legacyPath:managedPath}async installNpm(source,scope,temporary){let installRoot=getNpmInstallRoot(this.context,scope,temporary);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,[source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);if(!existsSync16(installRoot))return;let packageManagerName=getPackageManagerName(this.context);if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync16(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=getGitInstallRoot(this.context,scope);gitRoot&&ensureGitIgnore(gitRoot),mkdirSync11(dirname23(targetDir),{recursive:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}catch(error2){throw rmSync4(targetDir,{recursive:!0,force:!0}),pruneEmptyGitParents(targetDir,gitRoot),error2}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync16(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}async repairMissingGitDependencies(targetDir){hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error2){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error2}let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir}),rmSync4(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),markerPath=getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync16(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync10(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled2())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync4(targetDir,{recursive:!0,force:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0}),pruneEmptyGitParents(targetDir,getGitInstallRoot(this.context,scope))}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}spawnCommand(command,args,options){let env2=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env:env2})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env2=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env:env2})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,child.kill()},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error2=>{timeout&&clearTimeout(timeout),reject2(error2)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject2(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject2(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject2),child.on("exit",code=>{code===0?resolvePromise():reject2(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env2=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:env2});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{randomUUID as randomUUID15}from"crypto";import{existsSync as existsSync17,mkdirSync as mkdirSync12,readFileSync as readFileSync16,writeFileSync as writeFileSync11}from"fs";import{dirname as dirname24,join as join43}from"path";function isMergeableObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function deepMergeObjects(base,overrides){let result={...base};for(let key of Object.keys(overrides)){let overrideValue=overrides[key];if(overrideValue===void 0)continue;let baseValue=base[key];result[key]=isMergeableObject(baseValue)&&isMergeableObject(overrideValue)?deepMergeObjects(baseValue,overrideValue):overrideValue}return result}function deepMergeSettings(base,overrides){return deepMergeObjects(base,overrides)}function parseTimeoutSetting(value,settingName){let timeoutMs=parseHttpIdleTimeoutMs(value);if(timeoutMs!==void 0)return timeoutMs;if(value!==void 0)throw new Error(`Invalid ${settingName} setting: ${String(value)}`)}function toSettingsError(scope,error2,path15){return{scope,...path15?{path:path15}:{},error:error2 instanceof Error?error2:new Error(String(error2))}}var FileSettingsStorage=class{globalSettingsPath;projectSettingsPath;constructor(cwd,agentDir){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir);this.globalSettingsPath=join43(resolvedAgentDir,"settings.json"),this.projectSettingsPath=join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")}acquireLockSyncWithRetry(path15){let lastError;for(let attempt2=1;attempt2<=10;attempt2++)try{return import_proper_lockfile2.default.lockSync(path15,{realpath:!1})}catch(error2){if((typeof error2=="object"&&error2!==null&&"code"in error2?String(error2.code):void 0)!=="ELOCKED"||attempt2===10)throw error2;lastError=error2;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire settings lock")}withLock(scope,fn){let path15=scope==="global"?this.globalSettingsPath:this.projectSettingsPath,dir=dirname24(path15),release;try{let fileExists2=existsSync17(path15);fileExists2&&(release=this.acquireLockSyncWithRetry(path15));let current=fileExists2?readFileSync16(path15,"utf-8"):void 0,next=fn(current);next!==void 0&&(existsSync17(dir)||mkdirSync12(dir,{recursive:!0}),release||(release=this.acquireLockSyncWithRetry(path15)),writeFileSync11(path15,next,"utf-8"))}finally{release&&release()}}},InMemorySettingsStorage=class{global;project;withLock(scope,fn){let current=scope==="global"?this.global:this.project,next=fn(current);next!==void 0&&(scope==="global"?this.global=next:this.project=next)}},SettingsManager=class _SettingsManager{storage;globalSettings;projectSettings;settings;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(storage,initialGlobal,initialProject,globalLoadError=null,projectLoadError=null,initialErrors=[],settingsPaths={}){this.storage=storage,this.globalSettings=initialGlobal,this.projectSettings=initialProject,this.globalSettingsLoadError=globalLoadError,this.projectSettingsLoadError=projectLoadError,this.errors=[...initialErrors],this.settingsPaths=settingsPaths,this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}static create(cwd,agentDir=getAgentDir(),options={}){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),storage=new FileSettingsStorage(resolvedCwd,resolvedAgentDir);return _SettingsManager.fromStorageWithPaths(storage,options,{global:join43(resolvedAgentDir,"settings.json"),project:join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")})}static fromStorage(storage,options={}){return _SettingsManager.fromStorageWithPaths(storage,options)}static fromStorageWithPaths(storage,options,settingsPaths={}){let globalLoad=_SettingsManager.tryLoadFromStorage(storage,"global"),projectLoad=_SettingsManager.tryLoadFromStorage(storage,"project"),initialErrors=[];return globalLoad.error&&initialErrors.push(toSettingsError("global",globalLoad.error,settingsPaths.global)),projectLoad.error&&initialErrors.push(toSettingsError("project",projectLoad.error,settingsPaths.project)),new _SettingsManager(storage,globalLoad.settings,projectLoad.settings,globalLoad.error,projectLoad.error,initialErrors,settingsPaths)}static inMemory(settings2={},options={}){let storage=new InMemorySettingsStorage,initialSettings=_SettingsManager.migrateSettings(structuredClone(settings2));return storage.withLock("global",()=>JSON.stringify(initialSettings,null,2)),_SettingsManager.fromStorage(storage,options)}static loadFromStorage(storage,scope){let content;if(storage.withLock(scope,current=>{content=current}),!content)return{};let settings2=JSON.parse(stripBom(content));return _SettingsManager.migrateSettings(settings2)}static tryLoadFromStorage(storage,scope){try{return{settings:_SettingsManager.loadFromStorage(storage,scope),error:null}}catch(error2){return{settings:{},error:error2}}}static migrateSettings(settings2){if("queueMode"in settings2&&!("steeringMode"in settings2)&&(settings2.steeringMode=settings2.queueMode,delete settings2.queueMode),!("transport"in settings2)&&typeof settings2.websockets=="boolean"&&(settings2.transport=settings2.websockets?"websocket":"sse",delete settings2.websockets),"skills"in settings2&&typeof settings2.skills=="object"&&settings2.skills!==null&&!Array.isArray(settings2.skills)){let skillsSettings=settings2.skills;skillsSettings.enableSkillCommands!==void 0&&settings2.enableSkillCommands===void 0&&(settings2.enableSkillCommands=skillsSettings.enableSkillCommands),Array.isArray(skillsSettings.customDirectories)&&skillsSettings.customDirectories.length>0?settings2.skills=skillsSettings.customDirectories:delete settings2.skills}if("retry"in settings2&&typeof settings2.retry=="object"&&settings2.retry!==null&&!Array.isArray(settings2.retry)){let retrySettings=settings2.retry,providerSettings=typeof retrySettings.provider=="object"&&retrySettings.provider!==null?retrySettings.provider:void 0;typeof retrySettings.maxDelayMs=="number"&&(providerSettings?.maxRetryDelayMs===void 0||providerSettings?.maxRetryDelayMs===null)&&(retrySettings.provider={...providerSettings??{},maxRetryDelayMs:retrySettings.maxDelayMs}),delete retrySettings.maxDelayMs}return settings2}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let globalLoad=_SettingsManager.tryLoadFromStorage(this.storage,"global");globalLoad.error?(this.globalSettingsLoadError=globalLoad.error,this.recordError("global",globalLoad.error)):(this.globalSettings=globalLoad.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project");projectLoad.error?(this.projectSettingsLoadError=projectLoad.error,this.recordError("project",projectLoad.error)):(this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=null),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}applyOverrides(overrides){this.settings=deepMergeSettings(this.settings,overrides)}markModified(field2,nestedKey){this.modifiedFields.add(field2),nestedKey&&(this.modifiedNestedFields.has(field2)||this.modifiedNestedFields.set(field2,new Set),this.modifiedNestedFields.get(field2).add(nestedKey))}markProjectModified(field2,nestedKey){this.modifiedProjectFields.add(field2),nestedKey&&(this.modifiedProjectNestedFields.has(field2)||this.modifiedProjectNestedFields.set(field2,new Set),this.modifiedProjectNestedFields.get(field2).add(nestedKey))}recordError(scope,error2){this.errors.push(toSettingsError(scope,error2,this.settingsPaths[scope]))}clearModifiedScope(scope){if(scope==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(scope,task){this.writeQueue=this.writeQueue.then(()=>{task(),this.clearModifiedScope(scope)}).catch(error2=>{this.recordError(scope,error2)})}cloneModifiedNestedFields(source){let snapshot2=new Map;for(let[key,value]of source.entries())snapshot2.set(key,new Set(value));return snapshot2}persistScopedSettings(scope,snapshotSettings,modifiedFields,modifiedNestedFields){this.storage.withLock(scope,current=>{let currentFileSettings=current?_SettingsManager.migrateSettings(JSON.parse(stripBom(current))):{},mergedSettings={...currentFileSettings};for(let field2 of modifiedFields){let value=snapshotSettings[field2];if(modifiedNestedFields.has(field2)&&typeof value=="object"&&value!==null){let nestedModified=modifiedNestedFields.get(field2),baseNested=currentFileSettings[field2]??{},inMemoryNested=value,mergedNested={...baseNested};for(let nestedKey of nestedModified)mergedNested[nestedKey]=inMemoryNested[nestedKey];mergedSettings[field2]=mergedNested}else mergedSettings[field2]=value}return JSON.stringify(mergedSettings,null,2)})}save(){if(this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let snapshotGlobalSettings=structuredClone(this.globalSettings),modifiedFields=new Set(this.modifiedFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",snapshotGlobalSettings,modifiedFields,modifiedNestedFields)})}saveProjectSettings(settings2){if(this.projectSettings=structuredClone(settings2),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let snapshotProjectSettings=structuredClone(this.projectSettings),modifiedFields=new Set(this.modifiedProjectFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",snapshotProjectSettings,modifiedFields,modifiedNestedFields)})}updateProjectSettings(field2,update){let projectSettings=structuredClone(this.projectSettings);update(projectSettings),this.markProjectModified(field2),this.saveProjectSettings(projectSettings)}async flush(){await this.writeQueue}drainErrors(){let drained=[...this.errors];return this.errors=[],drained}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(version){this.globalSettings.lastChangelogVersion=version,this.markModified("lastChangelogVersion"),this.save()}getSuiteNoticeAcknowledgement(suiteId){return this.settings.suiteNoticesAcknowledged?.[suiteId]}setSuiteNoticeAcknowledgement(suiteId,ack){let next={...this.globalSettings.suiteNoticesAcknowledged??{},...this.settings.suiteNoticesAcknowledged??{}},existing=next[suiteId];next[suiteId]={...typeof existing=="object"&&existing!==null?existing:{},...ack.driftDigest===void 0?{}:{driftDigest:ack.driftDigest},...ack.upgradeRevision===void 0?{}:{upgradeRevision:ack.upgradeRevision}},this.globalSettings.suiteNoticesAcknowledged=next,this.settings.suiteNoticesAcknowledged=next,this.markModified("suiteNoticesAcknowledged"),this.save()}getSessionDir(){let sessionDir=this.settings.sessionDir;return sessionDir&&normalizePath(sessionDir)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}getMemoryModeSetting(){return this.settings.memory?.mode}setDefaultProvider(provider){this.globalSettings.defaultProvider=provider,this.markModified("defaultProvider"),this.save()}setDefaultModel(modelId){this.globalSettings.defaultModel=modelId,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(provider,modelId){this.globalSettings.defaultProvider=provider,this.globalSettings.defaultModel=modelId,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(mode){this.globalSettings.steeringMode=mode,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(mode){this.globalSettings.followUpMode=mode,this.markModified("followUpMode"),this.save()}getThemeSetting(){let value=this.settings.theme;if(typeof value=="string")return value}getTheme(){let theme2=this.getThemeSetting();return theme2?.includes("/")?void 0:theme2}setTheme(theme2){this.globalSettings.theme=theme2,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(level){this.globalSettings.defaultThinkingLevel=level,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(provider,modelId){return this.settings.modelThinkingLevels?.[`${provider}/${modelId}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(provider,modelId,level){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`]=level,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(provider,modelId){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(transport){this.globalSettings.transport=transport,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(enabled){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=enabled,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(enabled){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=enabled,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??5,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS}}getHttpIdleTimeoutMs(){return parseTimeoutSetting(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??DEFAULT_HTTP_IDLE_TIMEOUT_MS}setHttpIdleTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs)||timeoutMs<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(timeoutMs),this.markModified("httpIdleTimeoutMs"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){let configuredEditor=this.settings.externalEditor;if(typeof configuredEditor=="string"&&configuredEditor.trim()!=="")return configuredEditor;let environmentEditor=process.env.VISUAL||process.env.EDITOR;return environmentEditor||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(hide){this.globalSettings.hideThinkingBlock=hide,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(show){this.globalSettings.showCacheMissNotices=show,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){let shellPath=this.settings.shellPath;return shellPath&&normalizePath(shellPath)}setShellPath(path15){this.globalSettings.shellPath=path15,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(quiet){this.globalSettings.quietStartup=quiet,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(prefix){this.globalSettings.shellCommandPrefix=prefix,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(command){this.globalSettings.npmCommand=command?[...command]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(collapse){this.globalSettings.collapseChangelog=collapse,this.markModified("collapseChangelog"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(enabled){this.globalSettings.enableAnalytics=enabled,this.markModified("enableAnalytics"),enabled&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=randomUUID15(),this.markModified("trackingId")),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(packages){this.globalSettings.packages=packages,this.markModified("packages"),this.save()}setProjectPackages(packages){this.updateProjectSettings("packages",settings2=>{settings2.packages=packages})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(paths){this.globalSettings.skills=paths,this.markModified("skills"),this.save()}setProjectSkillPaths(paths){this.updateProjectSettings("skills",settings2=>{settings2.skills=paths})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(paths){this.globalSettings.prompts=paths,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(paths){this.updateProjectSettings("prompts",settings2=>{settings2.prompts=paths})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(paths){this.globalSettings.themes=paths,this.markModified("themes"),this.save()}setProjectThemePaths(paths){this.updateProjectSettings("themes",settings2=>{settings2.themes=paths})}setProjectSuite(id){this.updateProjectSettings("suite",settings2=>{if(id===void 0){delete settings2.suite;return}settings2.suite=id})}setSuite(id){id===void 0?delete this.globalSettings.suite:this.globalSettings.suite=id,this.markModified("suite"),this.save()}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(enabled){this.globalSettings.enableSkillCommands=enabled,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){let terminal=this.settings.terminal,images=terminal?.images;return{...images==="kitty"||images==="iterm2"?{images}:images===!1?{images:null}:{},...typeof terminal?.trueColor=="boolean"?{trueColor:terminal.trueColor}:{},...typeof terminal?.hyperlinks=="boolean"?{hyperlinks:terminal.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(show){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=show,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){let width=this.settings.terminal?.imageWidthCells;return typeof width!="number"||!Number.isFinite(width)?60:Math.max(1,Math.floor(width))}setImageWidthCells(width){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(width)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){if(this.settings.terminal?.clearOnShrink!==void 0)return this.settings.terminal.clearOnShrink;let configuredValue=process.env.AGENT_FORGE_CLEAR_ON_SHRINK;return configuredValue===void 0?process.env.PI_CLEAR_ON_SHRINK==="1":configuredValue==="1"}setClearOnShrink(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=enabled,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(enabled){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=enabled,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":"regular"}setTuiMode(mode){this.globalSettings.tuiMode=mode,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(output){this.globalSettings.fullscreenExitOutput=output,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){let mode=this.settings.fullscreenScrollbar;return mode==="always"||mode==="hidden"?mode:"auto"}setFullscreenScrollbar(mode){this.globalSettings.fullscreenScrollbar=mode,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(enabled){this.globalSettings.fullscreenCopyOnSelect=enabled,this.markModified("fullscreenCopyOnSelect"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(enabled){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=enabled,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(blocked){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=blocked,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){let tools=this.settings.defaultTools;return tools?[...tools]:void 0}setEnabledModels(patterns){this.globalSettings.enabledModels=patterns,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(action){this.globalSettings.doubleEscapeAction=action,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){let mode=this.settings.treeFilterMode;return mode&&["default","no-tools","user-only","labeled-only","all"].includes(mode)?mode:"default"}setTreeFilterMode(mode){this.globalSettings.treeFilterMode=mode,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){if(this.settings.showHardwareCursor!==void 0)return this.settings.showHardwareCursor;let configuredValue=process.env.AGENT_FORGE_HARDWARE_CURSOR;return configuredValue===void 0?process.env.PI_HARDWARE_CURSOR==="1":configuredValue==="1"}setShowHardwareCursor(enabled){this.globalSettings.showHardwareCursor=enabled,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(padding){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(padding))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===0?0:1}setOutputPad(padding){this.globalSettings.outputPad=padding,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(maxVisible){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(maxVisible))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){let mode=this.settings.markdown?.mermaid;return mode==="off"||mode==="final"?mode:"streaming"}setMermaidRenderingMode(mode){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=mode,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(warnings){this.globalSettings.warnings={...warnings},this.markModified("warnings"),this.save()}};import{existsSync as existsSync19,readdirSync as readdirSync13,readFileSync as readFileSync18,statSync as statSync15}from"node:fs";import{basename as basename12,dirname as dirname26,join as join45,resolve as resolve16,sep as sep10}from"node:path";import{execFile,spawnSync as spawnSync4}from"child_process";import{existsSync as existsSync18,readFileSync as readFileSync17,statSync as statSync14,unwatchFile,watchFile}from"fs";import{dirname as dirname25,join as join44,resolve as resolve15}from"path";function findGitPaths(cwd){let dir=cwd;for(;;){let gitPath=join44(dir,".git");if(existsSync18(gitPath))try{let stat5=statSync14(gitPath);if(stat5.isFile()){let content=readFileSync17(gitPath,"utf8").trim();if(content.startsWith("gitdir: ")){let gitDir=resolve15(dir,content.slice(8).trim()),headPath=join44(gitDir,"HEAD");if(!existsSync18(headPath))return null;let commonDirPath=join44(gitDir,"commondir"),commonGitDir=existsSync18(commonDirPath)?resolve15(gitDir,readFileSync17(commonDirPath,"utf8").trim()):gitDir;return{repoDir:dir,commonGitDir,headPath}}}else if(stat5.isDirectory()){let headPath=join44(gitPath,"HEAD");return existsSync18(headPath)?{repoDir:dir,commonGitDir:gitPath,headPath}:null}}catch{return null}let parent=dirname25(dir);if(parent===dir)return null;dir=parent}}function resolveBranchWithGitSync(repoDir){let result=spawnSync4("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return(result.status===0?result.stdout.trim():"")||null}function resolveBranchWithGitAsync(repoDir){return new Promise(resolvePromise=>{execFile("git",["--no-optional-locks","symbolic-ref","--quiet","--short","HEAD"],{cwd:repoDir,encoding:"utf8"},(error2,stdout)=>{if(error2){resolvePromise(null);return}let branch=stdout.trim();resolvePromise(branch||null)})})}function isWslEnvironment(){return process.platform==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)}function isWindowsMountedRepoPath(repoDir){return/^\/mnt\/[a-z](?:\/|$)/i.test(repoDir)}function shouldPollGitHead(repoDir){return isWslEnvironment()&&isWindowsMountedRepoPath(repoDir)}var FooterDataProvider=class _FooterDataProvider{cwd;static WATCH_DEBOUNCE_MS=500;cachedBranch=void 0;gitPaths=void 0;headWatcher=null;headWatchFilePath=null;headWatchFileListener=null;reftableWatcher=null;reftableTablesListWatcher=null;reftableTablesListPath=null;branchChangeCallbacks=new Set;availableProviderCount=0;refreshTimer=null;gitWatcherRetryTimer=null;refreshInFlight=!1;refreshPending=!1;disposed=!1;constructor(cwd){this.cwd=cwd,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher()}getGitBranch(){return this.cachedBranch===void 0&&(this.cachedBranch=this.resolveGitBranchSync()),this.cachedBranch}onBranchChange(callback){return this.branchChangeCallbacks.add(callback),()=>this.branchChangeCallbacks.delete(callback)}getAvailableProviderCount(){return this.availableProviderCount}setAvailableProviderCount(count){this.availableProviderCount=count}setCwd(cwd){this.cwd!==cwd&&(this.cwd=cwd,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.cachedBranch=void 0,this.gitPaths=findGitPaths(cwd),this.setupGitWatcher(),this.notifyBranchChange())}dispose(){this.disposed=!0,this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null),this.clearGitWatchers(),this.branchChangeCallbacks.clear()}notifyBranchChange(){for(let cb of this.branchChangeCallbacks)cb()}scheduleRefresh(){if(!(this.disposed||this.refreshTimer)){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.refreshGitBranchAsync()},_FooterDataProvider.WATCH_DEBOUNCE_MS)}}async refreshGitBranchAsync(){if(!this.disposed){if(this.refreshInFlight){this.refreshPending=!0;return}this.refreshInFlight=!0;try{let nextBranch=await this.resolveGitBranchAsync();if(this.disposed)return;if(this.cachedBranch!==void 0&&this.cachedBranch!==nextBranch){this.cachedBranch=nextBranch,this.notifyBranchChange();return}this.cachedBranch=nextBranch}finally{this.refreshInFlight=!1,this.refreshPending&&!this.disposed&&(this.refreshPending=!1,this.scheduleRefresh())}}}resolveGitBranchSync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?resolveBranchWithGitSync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}async resolveGitBranchAsync(){try{if(!this.gitPaths)return null;let content=readFileSync17(this.gitPaths.headPath,"utf8").trim();if(content.startsWith("ref: refs/heads/")){let branch=content.slice(16);return branch===".invalid"?await resolveBranchWithGitAsync(this.gitPaths.repoDir)??"detached":branch}return"detached"}catch{return null}}clearGitWatchers(){closeWatcher(this.headWatcher),this.headWatcher=null,this.headWatchFilePath&&this.headWatchFileListener&&(unwatchFile(this.headWatchFilePath,this.headWatchFileListener),this.headWatchFilePath=null,this.headWatchFileListener=null),closeWatcher(this.reftableWatcher),this.reftableWatcher=null,closeWatcher(this.reftableTablesListWatcher),this.reftableTablesListWatcher=null,this.reftableTablesListPath&&(unwatchFile(this.reftableTablesListPath),this.reftableTablesListPath=null),this.gitWatcherRetryTimer&&(clearTimeout(this.gitWatcherRetryTimer),this.gitWatcherRetryTimer=null)}scheduleGitWatcherRetry(){this.disposed||this.gitWatcherRetryTimer||(this.gitWatcherRetryTimer=setTimeout(()=>{this.gitWatcherRetryTimer=null,this.setupGitWatcher()},FS_WATCH_RETRY_DELAY_MS))}handleGitWatcherError(){this.clearGitWatchers(),this.scheduleGitWatcherRetry()}setupGitWatcher(){if(this.clearGitWatchers(),!this.gitPaths)return;let pollGitHead=shouldPollGitHead(this.gitPaths.repoDir);if(this.headWatcher=watchWithErrorHandler(dirname25(this.gitPaths.headPath),(_eventType,filename)=>{(!filename||filename==="HEAD")&&this.scheduleRefresh()},()=>this.handleGitWatcherError()),pollGitHead&&(this.headWatchFilePath=this.gitPaths.headPath,this.headWatchFileListener=(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()},watchFile(this.headWatchFilePath,{interval:1e3},this.headWatchFileListener)),!this.headWatcher&&!pollGitHead)return;let reftableDir=join44(this.gitPaths.commonGitDir,"reftable");if(existsSync18(reftableDir)){if(this.reftableWatcher=watchWithErrorHandler(reftableDir,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableWatcher)return;let tablesListPath=join44(reftableDir,"tables.list");if(existsSync18(tablesListPath)){if(this.reftableTablesListPath=tablesListPath,this.reftableTablesListWatcher=watchWithErrorHandler(tablesListPath,()=>{this.scheduleRefresh()},()=>this.handleGitWatcherError()),!this.reftableTablesListWatcher)return;watchFile(tablesListPath,{interval:250},(current,previous)=>{(current.mtimeMs!==previous.mtimeMs||current.ctimeMs!==previous.ctimeMs||current.size!==previous.size)&&this.scheduleRefresh()})}}}};function resolvePromptInput(input,description){if(input){if(existsSync19(input))try{return stripBom(readFileSync18(input,"utf-8"))}catch(error2){return console.error(source_default.yellow(`Warning: Could not read ${description} file ${input}: ${error2}`)),input}return input}}function loadContextFileFromDir(dir){let candidates=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(let filename of candidates){let filePath=join45(dir,filename);if(existsSync19(filePath))try{if(!statSync15(filePath).isFile())continue;return{path:filePath,content:stripBom(readFileSync18(filePath,"utf-8"))}}catch(error2){console.error(source_default.yellow(`Warning: Could not read ${filePath}: ${error2}`))}}return null}function findShadowedContextFile(cwd){let gitPaths=findGitPaths(cwd);if(!gitPaths)return;let commonGitDir=canonicalizePath(gitPaths.commonGitDir),worktreeRoot=canonicalizePath(gitPaths.repoDir),mainRepoRoot=dirname26(commonGitDir);if(!worktreeRoot.startsWith(`${mainRepoRoot}${sep10}`)||canonicalizePath(join45(mainRepoRoot,".git"))!==commonGitDir)return;let worktreeContextFile=loadContextFileFromDir(worktreeRoot);return worktreeContextFile?join45(mainRepoRoot,basename12(worktreeContextFile.path)):void 0}function loadProjectContextFiles(options){let resolvedCwd=resolvePath(options.cwd),resolvedAgentDir=resolvePath(options.agentDir),contextFiles=[],seenPaths=new Set,globalContext=loadContextFileFromDir(resolvedAgentDir);globalContext&&(contextFiles.push(globalContext),seenPaths.add(globalContext.path));let ancestorContextFiles=[],shadowedContextFile=findShadowedContextFile(resolvedCwd),currentDir=resolvedCwd;for(;;){let contextFile=loadContextFileFromDir(currentDir),isShadowed=shadowedContextFile!==void 0&&canonicalizePath(contextFile?.path??"")===shadowedContextFile;contextFile&&!isShadowed&&!seenPaths.has(contextFile.path)&&(ancestorContextFiles.unshift(contextFile),seenPaths.add(contextFile.path));let parentDir=dirname26(currentDir);if(parentDir===currentDir)break;currentDir=parentDir}return contextFiles.push(...ancestorContextFiles),contextFiles}var DefaultResourceLoader=class{cwd;agentDir;settingsManager;packageManager;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager??SettingsManager.create(this.cwd,this.agentDir),this.packageManager=new DefaultPackageManager({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}),this.additionalSkillPaths=options.additionalSkillPaths??[],this.additionalPromptTemplatePaths=options.additionalPromptTemplatePaths??[],this.additionalThemePaths=options.additionalThemePaths??[],this.noSkills=options.noSkills??!1,this.noPromptTemplates=options.noPromptTemplates??!1,this.noThemes=options.noThemes??!1,this.noContextFiles=options.noContextFiles??!1,this.systemPromptSource=options.systemPrompt,this.appendSystemPromptSource=options.appendSystemPrompt,this.skillsOverride=options.skillsOverride,this.promptsOverride=options.promptsOverride,this.themesOverride=options.themesOverride,this.agentsFilesOverride=options.agentsFilesOverride,this.systemPromptOverride=options.systemPromptOverride,this.appendSystemPromptOverride=options.appendSystemPromptOverride,this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[]}getSkills(){return{skills:this.skills.slice(),diagnostics:this.skillDiagnostics.slice()}}getPrompts(){return{prompts:this.prompts.slice(),diagnostics:this.promptDiagnostics.slice()}}getThemes(){return{themes:this.themes.slice(),diagnostics:this.themeDiagnostics.slice()}}getAgentsFiles(){return{agentsFiles:this.agentsFiles.slice()}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(path15=>({path:path15}))}extendResources(paths){let skillPaths=this.normalizeExtensionPaths(paths.skillPaths??[]),promptPaths=this.normalizeExtensionPaths(paths.promptPaths??[]),themePaths=this.normalizeExtensionPaths(paths.themePaths??[]);for(let entry of skillPaths)this.extensionSkillSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of promptPaths)this.extensionPromptSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));for(let entry of themePaths)this.extensionThemeSourceInfos.set(entry.path,createSourceInfo(entry.path,entry.metadata));skillPaths.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,skillPaths.map(entry=>entry.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),promptPaths.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,promptPaths.map(entry=>entry.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),themePaths.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,themePaths.map(entry=>entry.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async reload(_options){await this.settingsManager.reload();let resolvedPaths=await this.packageManager.resolve();this.resourceMetadataByPath=new Map;let metadataByPath=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;let getEnabledResources=resources=>{for(let r of resources)metadataByPath.has(r.path)||metadataByPath.set(r.path,r.metadata);return resources.filter(r=>r.enabled)},getEnabledPaths=resources=>getEnabledResources(resources).map(r=>r.path),enabledSkillResources=getEnabledResources(resolvedPaths.skills),enabledPrompts=getEnabledPaths(resolvedPaths.prompts),enabledThemes=getEnabledPaths(resolvedPaths.themes),enabledSkills=enabledSkillResources.map(resource=>this.mapSkillPath(resource,metadataByPath)),skillPaths=this.noSkills?[...this.additionalSkillPaths]:this.mergePaths(enabledSkills,this.additionalSkillPaths);this.lastSkillPaths=skillPaths,this.updateSkillsFromPaths(skillPaths,metadataByPath);for(let p of this.additionalSkillPaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.skillDiagnostics.some(d2=>d2.path===resolved)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:resolved})}let promptPaths=this.noPromptTemplates?[...this.additionalPromptTemplatePaths]:this.mergePaths(enabledPrompts,this.additionalPromptTemplatePaths);this.lastPromptPaths=promptPaths,this.updatePromptsFromPaths(promptPaths,metadataByPath);for(let p of this.additionalPromptTemplatePaths)if(isLocalPath(p)){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.promptDiagnostics.some(d2=>d2.path===resolved)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:resolved})}let themePaths=this.noThemes?[...this.additionalThemePaths]:this.mergePaths(enabledThemes,this.additionalThemePaths);this.lastThemePaths=themePaths,this.updateThemesFromPaths(themePaths,metadataByPath);for(let p of this.additionalThemePaths){let resolved=this.resolveResourcePath(p);!existsSync19(resolved)&&!this.themeDiagnostics.some(d2=>d2.path===resolved)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:resolved})}let agentsFiles={agentsFiles:this.noContextFiles?[]:loadProjectContextFiles({cwd:this.cwd,agentDir:this.agentDir})},resolvedAgentsFiles=this.agentsFilesOverride?this.agentsFilesOverride(agentsFiles):agentsFiles;this.agentsFiles=resolvedAgentsFiles.agentsFiles;let systemPromptSource=this.systemPromptSource??this.discoverSystemPromptFile(),baseSystemPrompt=resolvePromptInput(systemPromptSource,"system prompt");this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(baseSystemPrompt):baseSystemPrompt,this.systemPromptSourcePath=systemPromptSource&&existsSync19(systemPromptSource)?resolvePath(systemPromptSource):void 0;let appendSources=this.appendSystemPromptSource;if(!appendSources){let discoveredAppendSystemPromptFile=this.discoverAppendSystemPromptFile();appendSources=discoveredAppendSystemPromptFile?[discoveredAppendSystemPromptFile]:[]}let baseAppend=appendSources.map(s=>resolvePromptInput(s,"append system prompt")).filter(s=>s!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(baseAppend):baseAppend,this.appendSystemPromptSourcePaths=appendSources.filter(source=>existsSync19(source)).map(source=>resolvePath(source))}mapSkillPath(resource,metadataByPath){if(resource.metadata.source!=="auto"&&resource.metadata.origin!=="package")return resource.path;try{if(!statSync15(resource.path).isDirectory())return resource.path}catch{return resource.path}let skillFile=join45(resource.path,"SKILL.md");return existsSync19(skillFile)?(metadataByPath.has(skillFile)||metadataByPath.set(skillFile,resource.metadata),skillFile):resource.path}normalizeExtensionPaths(entries){return entries.map(entry=>{let metadata=entry.metadata.baseDir?{...entry.metadata,baseDir:this.resolveResourcePath(entry.metadata.baseDir)}:entry.metadata;return{path:this.resolveResourcePath(entry.path),metadata}})}updateSkillsFromPaths(skillPaths,metadataByPath){let skillsResult;this.noSkills&&skillPaths.length===0?skillsResult={skills:[],diagnostics:[]}:skillsResult=loadSkills({cwd:this.cwd,agentDir:this.agentDir,skillPaths,includeDefaults:!1});let applySourceInfo=skill=>({...skill,sourceInfo:this.findSourceInfoForPath(skill.filePath,this.extensionSkillSourceInfos,metadataByPath)??skill.sourceInfo??this.getDefaultSourceInfoForPath(skill.filePath)});skillsResult={skills:skillsResult.skills.map(applySourceInfo),diagnostics:skillsResult.diagnostics};let resolvedSkills=this.skillsOverride?this.skillsOverride(skillsResult):skillsResult;this.skills=resolvedSkills.skills.map(applySourceInfo),this.skillDiagnostics=resolvedSkills.diagnostics}updatePromptsFromPaths(promptPaths,metadataByPath){let promptsResult;if(this.noPromptTemplates&&promptPaths.length===0)promptsResult={prompts:[],diagnostics:[]};else{let allPrompts=loadPromptTemplates({cwd:this.cwd,agentDir:this.agentDir,promptPaths,includeDefaults:!1});promptsResult=this.dedupePrompts(allPrompts)}let resolvedPrompts=this.promptsOverride?this.promptsOverride(promptsResult):promptsResult;this.prompts=resolvedPrompts.prompts.map(prompt=>({...prompt,sourceInfo:this.findSourceInfoForPath(prompt.filePath,this.extensionPromptSourceInfos,metadataByPath)??prompt.sourceInfo??this.getDefaultSourceInfoForPath(prompt.filePath)})),this.promptDiagnostics=resolvedPrompts.diagnostics}updateThemesFromPaths(themePaths,metadataByPath){let loadedThemes,themeDiagnostics;if(this.noThemes&&themePaths.length===0)loadedThemes=[],themeDiagnostics=[];else{let loaded=this.loadThemes(themePaths,!1),deduped=this.dedupeThemes(loaded.themes);loadedThemes=deduped.themes,themeDiagnostics=[...loaded.diagnostics,...deduped.diagnostics]}let themesResult={themes:loadedThemes.map(theme2=>this.buildThemeMeta(theme2,metadataByPath)),diagnostics:themeDiagnostics},resolvedThemes=this.themesOverride?this.themesOverride(themesResult):themesResult;this.themes=resolvedThemes.themes.map(meta=>this.buildThemeMeta(meta,metadataByPath)),this.themeDiagnostics=resolvedThemes.diagnostics}buildThemeMeta(source,metadataByPath){let sourcePath=source.sourcePath??"";return{name:source.name,sourcePath,sourceInfo:sourcePath?this.findSourceInfoForPath(sourcePath,this.extensionThemeSourceInfos,metadataByPath)??source.sourceInfo??this.getDefaultSourceInfoForPath(sourcePath):source.sourceInfo}}findSourceInfoForPath(resourcePath,extraSourceInfos,metadataByPath){if(!resourcePath)return;if(resourcePath.startsWith("<"))return this.getDefaultSourceInfoForPath(resourcePath);let normalizedResourcePath=resolve16(resourcePath);if(extraSourceInfos)for(let[sourcePath,sourceInfo]of extraSourceInfos.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return{...sourceInfo,path:resourcePath}}if(metadataByPath){let exact=metadataByPath.get(normalizedResourcePath)??metadataByPath.get(resourcePath);if(exact)return createSourceInfo(resourcePath,exact);for(let[sourcePath,metadata]of metadataByPath.entries()){let normalizedSourcePath=resolve16(sourcePath);if(normalizedResourcePath===normalizedSourcePath||normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep10}`))return createSourceInfo(resourcePath,metadata)}}}getDefaultSourceInfoForPath(filePath){if(filePath.startsWith("<")&&filePath.endsWith(">"))return{path:filePath,source:filePath.slice(1,-1).split(":")[0]||"temporary",scope:"temporary",origin:"top-level"};let normalizedPath=resolve16(filePath),agentRoots=[join45(this.agentDir,"skills"),join45(this.agentDir,"prompts"),join45(this.agentDir,"themes")],projectRoots=[join45(this.cwd,CONFIG_DIR_NAME,"skills"),join45(this.cwd,CONFIG_DIR_NAME,"prompts"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let root of agentRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"user",origin:"top-level",baseDir:root};for(let root of projectRoots)if(this.isUnderPath(normalizedPath,root))return{path:filePath,source:"local",scope:"project",origin:"top-level",baseDir:root};return{path:filePath,source:"local",scope:"temporary",origin:"top-level",baseDir:statSync15(normalizedPath).isDirectory()?normalizedPath:resolve16(normalizedPath,"..")}}mergePaths(primary,additional){let merged=[],seen=new Set;for(let p of[...primary,...additional]){let resolved=this.resolveResourcePath(p),canonicalPath=canonicalizePath(resolved);seen.has(canonicalPath)||(seen.add(canonicalPath),merged.push(resolved))}return merged}resolveResourcePath(p){return resolvePath(p,this.cwd,{trim:!0})}loadThemes(paths,includeDefaults=!0){let themes=[],diagnostics=[];if(includeDefaults){let defaultDirs=[join45(this.agentDir,"themes"),join45(this.cwd,CONFIG_DIR_NAME,"themes")];for(let dir of defaultDirs)this.loadThemesFromDir(dir,themes,diagnostics)}for(let p of paths){let resolved=this.resolveResourcePath(p);if(!existsSync19(resolved)){diagnostics.push({type:"warning",message:"theme path does not exist",path:resolved});continue}try{let stats=statSync15(resolved);stats.isDirectory()?this.loadThemesFromDir(resolved,themes,diagnostics):stats.isFile()&&resolved.endsWith(".json")?this.loadThemeFromFile(resolved,themes,diagnostics):diagnostics.push({type:"warning",message:"theme path is not a json file",path:resolved})}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme path";diagnostics.push({type:"warning",message,path:resolved})}}return{themes,diagnostics}}loadThemesFromDir(dir,themes,diagnostics){if(existsSync19(dir))try{let entries=readdirSync13(dir,{withFileTypes:!0});for(let entry of entries){let isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync15(join45(dir,entry.name)).isFile()}catch{continue}isFile&&entry.name.endsWith(".json")&&this.loadThemeFromFile(join45(dir,entry.name),themes,diagnostics)}}catch(error2){let message=error2 instanceof Error?error2.message:"failed to read theme directory";diagnostics.push({type:"warning",message,path:dir})}}loadThemeFromFile(filePath,themes,diagnostics){try{themes.push(loadThemeFromPath(filePath))}catch(error2){let message=error2 instanceof Error?error2.message:"failed to load theme";diagnostics.push({type:"warning",message,path:filePath})}}dedupePrompts(prompts){let seen=new Map,diagnostics=[];for(let prompt of prompts){let existing=seen.get(prompt.name);existing?diagnostics.push({type:"collision",message:`name "/${prompt.name}" collision`,path:prompt.filePath,collision:{resourceType:"prompt",name:prompt.name,winnerPath:existing.filePath,loserPath:prompt.filePath}}):seen.set(prompt.name,prompt)}return{prompts:Array.from(seen.values()),diagnostics}}dedupeThemes(themes){let seen=new Map,diagnostics=[];for(let t of themes){let name=t.name??"unnamed",existing=seen.get(name);existing?diagnostics.push({type:"collision",message:`name "${name}" collision`,path:t.sourcePath,collision:{resourceType:"theme",name,winnerPath:existing.sourcePath??"<builtin>",loserPath:t.sourcePath??"<builtin>"}}):seen.set(name,t)}return{themes:Array.from(seen.values()),diagnostics}}discoverSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"SYSTEM.md");if(existsSync19(globalPath))return globalPath}discoverAppendSystemPromptFile(){let projectPath=join45(this.cwd,CONFIG_DIR_NAME,"APPEND_SYSTEM.md");if(existsSync19(projectPath))return projectPath;let globalPath=join45(this.agentDir,"APPEND_SYSTEM.md");if(existsSync19(globalPath))return globalPath}isUnderPath(target,root){let normalizedRoot=resolve16(root);if(target===normalizedRoot)return!0;let prefix=normalizedRoot.endsWith(sep10)?normalizedRoot:`${normalizedRoot}${sep10}`;return target.startsWith(prefix)}};import{existsSync as existsSync23,mkdirSync as mkdirSync15,readFileSync as readFileSync20,writeFileSync as writeFileSync12}from"node:fs";import{isAbsolute as isAbsolute10,join as join50,relative as relative8,sep as sep11}from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{existsSync as existsSync22,realpathSync as realpathSync4}from"node:fs";import{readFile as readFile9}from"node:fs/promises";import{join as join49,resolve as resolve18}from"node:path";var import_semver5=__toESM(require_semver2(),1);var BUILTIN_CAPABILITY_PACKAGE_IDS=Object.freeze({"builtin.goal":"agent-forge.plugin.goal","builtin.plan":"agent-forge.plugin.plan","builtin.todo-set":"agent-forge.plugin.todo-set","builtin.session-share":"agent-forge.plugin.session-share","builtin.subagent-delegate":"agent-forge.plugin.subagent-delegate","builtin.memory":"agent-forge.plugin.memory"});import{constants as constants7,copyFileSync,existsSync as existsSync21,mkdirSync as mkdirSync13}from"node:fs";import{basename as basename13,join as join46,parse as parse4,resolve as resolve17}from"node:path";import{existsSync as existsSync20}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync20(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
|
|
1059
|
+
`,"utf-8")}function getInstalledNpmVersion(installedPath){let packageJsonPath=join38(installedPath,"package.json");if(existsSync13(packageJsonPath))try{let content=readFileSync12(packageJsonPath,"utf-8");return JSON.parse(stripBom(content)).version}catch{return}}function installedNpmMatchesConfiguredVersion(source,installedPath){let installedVersion=getInstalledNpmVersion(installedPath);return installedVersion?source.range?(0,import_semver2.satisfies)(installedVersion,source.range):!0:!1}function hasMissingGitDependencies(targetDir){let packageJsonPath=join38(targetDir,"package.json");if(!existsSync13(packageJsonPath))return!1;try{let manifest=JSON.parse(stripBom(readFileSync12(packageJsonPath,"utf-8")));if(!manifest.dependencies||typeof manifest.dependencies!="object"||Array.isArray(manifest.dependencies))return!1;let nodeModulesDir=resolve12(targetDir,"node_modules");return Object.keys(manifest.dependencies).some(name=>{let dependencyPath=resolve12(nodeModulesDir,name);return dependencyPath.startsWith(`${nodeModulesDir}${sep8}`)?!existsSync13(dependencyPath):!1})}catch{return!1}}function getGitUpdateMarkerPath(targetDir){return join38(dirname20(targetDir),`.${basename10(targetDir)}.agent-forge-update-incomplete`)}function pruneEmptyGitParents(targetDir,installRoot){if(!installRoot)return;let resolvedRoot=resolve12(installRoot),current=dirname20(targetDir);for(;current.startsWith(resolvedRoot)&¤t!==resolvedRoot;){if(!existsSync13(current)){current=dirname20(current);continue}if(readdirSync11(current).length>0)break;try{rmSync3(current,{recursive:!0,force:!0})}catch{break}current=dirname20(current)}}import{readFileSync as readFileSync13}from"node:fs";function getEnv(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{let data=readFileSync13("/proc/self/environ","utf-8"),env2={};for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&(env2[entry.slice(0,idx)]=entry.slice(idx+1))}return env2}catch{return process.env}}function isOfflineModeEnabled2(){let value=process.env.AGENT_FORGE_OFFLINE;return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}async function runWithConcurrency(tasks,limit){if(tasks.length===0)return[];let results=new Array(tasks.length),nextIndex=0,workerCount=Math.max(1,Math.min(limit,tasks.length)),worker=async()=>{for(;;){let index3=nextIndex;if(nextIndex+=1,index3>=tasks.length)return;results[index3]=await tasks[index3]()}};return await Promise.all(Array.from({length:workerCount},()=>worker())),results}import{existsSync as existsSync15,statSync as statSync12}from"node:fs";import{dirname as dirname22,join as join41,resolve as resolve14}from"node:path";var import_ignore3=__toESM(require_ignore(),1);import{existsSync as existsSync14,globSync,readdirSync as readdirSync12,readFileSync as readFileSync14,statSync as statSync11}from"node:fs";import{basename as basename11,dirname as dirname21,join as join39,relative as relative6,resolve as resolve13,sep as sep9}from"node:path";var RESOURCE_TYPES=["skills","prompts","themes"],FILE_PATTERNS={skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},IGNORE_FILE_NAMES2=[".gitignore",".ignore",".fdignore"];function toPosixPath3(p){return p.split(sep9).join("/")}function prefixIgnorePattern2(line,prefix){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}function addIgnoreRules2(ig,dir,rootDir){let relativeDir=relative6(rootDir,dir),prefix=relativeDir?`${toPosixPath3(relativeDir)}/`:"";for(let filename of IGNORE_FILE_NAMES2){let ignorePath=join39(dir,filename);if(existsSync14(ignorePath))try{let patterns=readFileSync14(ignorePath,"utf-8").split(/\r?\n/).map(line=>prefixIgnorePattern2(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}catch{}}}function isPattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")||s.includes("*")||s.includes("?")}function isOverridePattern(s){return s.startsWith("!")||s.startsWith("+")||s.startsWith("-")}function hasGlobPattern(s){return s.includes("*")||s.includes("?")}function expandPackageGlob(pattern,root){return globSync(pattern,{cwd:root}).map(match2=>resolve13(root,match2)).filter(path15=>relative6(root,path15).split(sep9).every(segment2=>segment2===".."||!segment2.startsWith("."))).sort((a,b2)=>a<b2?-1:a>b2?1:0)}function splitPatterns(entries){let plain=[],patterns=[];for(let entry of entries)isPattern(entry)?patterns.push(entry):plain.push(entry);return{plain,patterns}}function collectFiles(dir,filePattern,skipNodeModules=!0,ignoreMatcher,rootDir){let files=[];if(!existsSync14(dir))return files;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let entries=readdirSync12(dir,{withFileTypes:!0});for(let entry of entries){if(entry.name.startsWith(".")||skipNodeModules&&entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath)),ignorePath=isDir?`${relPath}/`:relPath;ig.ignores(ignorePath)||(isDir?files.push(...collectFiles(fullPath,filePattern,skipNodeModules,ig,root)):isFile&&filePattern.test(entry.name)&&files.push(fullPath))}}catch{}return files}function collectSkillEntries(dir,mode,ignoreMatcher,rootDir){let entries=[];if(!existsSync14(dir))return entries;let root=rootDir??dir,ig=ignoreMatcher??(0,import_ignore3.default)();addIgnoreRules2(ig,dir,root);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name!=="SKILL.md")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&!ig.ignores(relPath))return entries.push(fullPath),entries}for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let stats=statSync11(fullPath);isDir=stats.isDirectory(),isFile=stats.isFile()}catch{continue}let relPath=toPosixPath3(relative6(root,fullPath));if(isFile&&entry.name.endsWith(".md")&&!ig.ignores(relPath)&&(mode==="project"&&dir===root||mode==="agents"&&dir!==root)){entries.push(fullPath);continue}isDir&&(ig.ignores(`${relPath}/`)||entries.push(...collectSkillEntries(fullPath,mode,ig,root)))}}catch{}return entries}function collectAutoSkillEntries(dir,mode){return collectSkillEntries(dir,mode)}function findGitRepoRoot(startDir){let dir=resolve13(startDir);for(;;){if(existsSync14(join39(dir,".git")))return dir;let parent=dirname21(dir);if(parent===dir)return null;dir=parent}}function collectAncestorAgentsSkillDirs(startDir){let skillDirs=[],resolvedStartDir=resolve13(startDir),gitRepoRoot=findGitRepoRoot(resolvedStartDir),dir=resolvedStartDir;for(;skillDirs.push(join39(dir,".agents","skills")),!(gitRepoRoot&&dir===gitRepoRoot);){let parent=dirname21(dir);if(parent===dir)break;dir=parent}return skillDirs}function collectAutoPromptEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".md")&&entries.push(fullPath)}}catch{}return entries}function collectAutoThemeEntries(dir){let entries=[];if(!existsSync14(dir))return entries;let ig=(0,import_ignore3.default)();addIgnoreRules2(ig,dir,dir);try{let dirEntries=readdirSync12(dir,{withFileTypes:!0});for(let entry of dirEntries){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=join39(dir,entry.name),isFile=entry.isFile();if(entry.isSymbolicLink())try{isFile=statSync11(fullPath).isFile()}catch{continue}let relPath=toPosixPath3(relative6(dir,fullPath));ig.ignores(relPath)||isFile&&entry.name.endsWith(".json")&&entries.push(fullPath)}}catch{}return entries}function collectResourceFiles(dir,resourceType){return resourceType==="skills"?collectSkillEntries(dir,"project"):collectFiles(dir,FILE_PATTERNS[resourceType])}function matchesAnyPattern(filePath,patterns,baseDir){let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentName=isSkillFile?basename11(parentDir):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalizedPattern=toPosixPath3(pattern);return minimatch(rel,normalizedPattern)||minimatch(name,normalizedPattern)||minimatch(filePathPosix,normalizedPattern)?!0:isSkillFile?minimatch(parentRel,normalizedPattern)||minimatch(parentName,normalizedPattern)||minimatch(parentDirPosix,normalizedPattern):!1})}function normalizeExactPattern(pattern){let normalized=pattern.startsWith("./")||pattern.startsWith(".\\")?pattern.slice(2):pattern;return toPosixPath3(normalized)}function matchesAnyExactPattern(filePath,patterns,baseDir){if(patterns.length===0)return!1;let rel=toPosixPath3(relative6(baseDir,filePath)),name=basename11(filePath),filePathPosix=toPosixPath3(filePath),isSkillFile=name==="SKILL.md",parentDir=isSkillFile?dirname21(filePath):void 0,parentRel=isSkillFile?toPosixPath3(relative6(baseDir,parentDir)):void 0,parentDirPosix=isSkillFile?toPosixPath3(parentDir):void 0;return patterns.some(pattern=>{let normalized=normalizeExactPattern(pattern);return normalized===rel||normalized===filePathPosix?!0:isSkillFile?normalized===parentRel||normalized===parentDirPosix:!1})}function getOverridePatterns(entries){return entries.filter(pattern=>pattern.startsWith("!")||pattern.startsWith("+")||pattern.startsWith("-"))}function isEnabledByOverrides(filePath,patterns,baseDir){let overrides=getOverridePatterns(patterns),excludes=overrides.filter(pattern=>pattern.startsWith("!")).map(pattern=>pattern.slice(1)),forceIncludes=overrides.filter(pattern=>pattern.startsWith("+")).map(pattern=>pattern.slice(1)),forceExcludes=overrides.filter(pattern=>pattern.startsWith("-")).map(pattern=>pattern.slice(1)),enabled=!0;return excludes.length>0&&matchesAnyPattern(filePath,excludes,baseDir)&&(enabled=!1),forceIncludes.length>0&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&(enabled=!0),forceExcludes.length>0&&matchesAnyExactPattern(filePath,forceExcludes,baseDir)&&(enabled=!1),enabled}function applyPatterns(allPaths,patterns,baseDir){let includes=[],excludes=[],forceIncludes=[],forceExcludes=[];for(let p of patterns)p.startsWith("+")?forceIncludes.push(p.slice(1)):p.startsWith("-")?forceExcludes.push(p.slice(1)):p.startsWith("!")?excludes.push(p.slice(1)):includes.push(p);let result;if(includes.length===0?result=[...allPaths]:result=allPaths.filter(filePath=>matchesAnyPattern(filePath,includes,baseDir)),excludes.length>0&&(result=result.filter(filePath=>!matchesAnyPattern(filePath,excludes,baseDir))),forceIncludes.length>0)for(let filePath of allPaths)!result.includes(filePath)&&matchesAnyExactPattern(filePath,forceIncludes,baseDir)&&result.push(filePath);return forceExcludes.length>0&&(result=result.filter(filePath=>!matchesAnyExactPattern(filePath,forceExcludes,baseDir))),new Set(result)}function applyAutoloadDisabledPatterns(allPaths,patterns,baseDir){let result=new Map;for(let pattern of patterns){let target=pattern.slice(pattern.startsWith("+")||pattern.startsWith("-")||pattern.startsWith("!")?1:0),enabled=!pattern.startsWith("-")&&!pattern.startsWith("!"),exact=pattern.startsWith("+")||pattern.startsWith("-");for(let filePath of allPaths)(exact?matchesAnyExactPattern(filePath,[target],baseDir):matchesAnyPattern(filePath,[target],baseDir))&&result.set(filePath,enabled)}return result}var import_semver3=__toESM(require_semver2(),1);import{homedir as homedir7}from"node:os";import{join as join40,relative as relative7}from"node:path";var import_hosted_git_info=__toESM(require_lib(),1);function splitRef(url){let scpLikeMatch=url.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch){let pathWithMaybeRef2=scpLikeMatch[2]??"",refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:{repo:`git@${scpLikeMatch[1]??""}:${repoPath2}`,ref:ref2}}if(url.includes("://"))try{let parsed=new URL(url),pathWithMaybeRef2=parsed.pathname.replace(/^\/+/,""),refSeparator2=pathWithMaybeRef2.indexOf("@");if(refSeparator2<0)return{repo:url};let repoPath2=pathWithMaybeRef2.slice(0,refSeparator2),ref2=pathWithMaybeRef2.slice(refSeparator2+1);return!repoPath2||!ref2?{repo:url}:(parsed.pathname=`/${repoPath2}`,{repo:parsed.toString().replace(/\/$/,""),ref:ref2})}catch{return{repo:url}}let slashIndex=url.indexOf("/");if(slashIndex<0)return{repo:url};let host=url.slice(0,slashIndex),pathWithMaybeRef=url.slice(slashIndex+1),refSeparator=pathWithMaybeRef.indexOf("@");if(refSeparator<0)return{repo:url};let repoPath=pathWithMaybeRef.slice(0,refSeparator),ref=pathWithMaybeRef.slice(refSeparator+1);return!repoPath||!ref?{repo:url}:{repo:`${host}/${repoPath}`,ref}}function decodeForValidation(value){try{return decodeURIComponent(value)}catch{return null}}function hasUnsafeGitInstallPart(value,allowSlash){let decoded=decodeForValidation(value);if(decoded===null)return!0;let candidates=[value,decoded];for(let candidate of candidates)if(candidate.includes("\0")||candidate.includes("\\")||candidate.startsWith("/")||!allowSlash&&candidate.includes("/")||candidate.split("/").includes(".."))return!0;return!1}function buildGitSource(args){if(args.path.startsWith("/"))return null;let normalizedPath=args.path.replace(/\.git$/,"").replace(/^\/+/,"");return!args.host||!normalizedPath||normalizedPath.split("/").length<2||hasUnsafeGitInstallPart(args.host,!1)||hasUnsafeGitInstallPart(normalizedPath,!0)?null:{type:"git",repo:args.repo,host:args.host,path:normalizedPath,ref:args.ref,pinned:!!args.ref}}function parseGenericGitUrl(url){let{repo:repoWithoutRef,ref}=splitRef(url),repo=repoWithoutRef,host="",path15="",scpLikeMatch=repoWithoutRef.match(/^git@([^:]+):(.+)$/);if(scpLikeMatch)host=scpLikeMatch[1]??"",path15=scpLikeMatch[2]??"";else if(repoWithoutRef.startsWith("https://")||repoWithoutRef.startsWith("http://")||repoWithoutRef.startsWith("ssh://")||repoWithoutRef.startsWith("git://"))try{let parsed=new URL(repoWithoutRef);host=parsed.hostname,path15=parsed.pathname.replace(/^\/+/,"")}catch{return null}else{let slashIndex=repoWithoutRef.indexOf("/");if(slashIndex<0||(host=repoWithoutRef.slice(0,slashIndex),path15=repoWithoutRef.slice(slashIndex+1),!host.includes(".")&&host!=="localhost"))return null;repo=`https://${repoWithoutRef}`}return buildGitSource({repo,host,path:path15,ref})}function parseGitUrl(source){let trimmed=source.trim(),hasGitPrefix=trimmed.startsWith("git:"),url=hasGitPrefix?trimmed.slice(4).trim():trimmed;if(!hasGitPrefix&&!/^(https?|ssh|git):\/\//i.test(url))return null;let split=splitRef(url),hostedCandidates=[split.ref?`${split.repo}#${split.ref}`:void 0,url].filter(value=>!!value);for(let candidate of hostedCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;let useHttpsPrefix=!split.repo.startsWith("http://")&&!split.repo.startsWith("https://")&&!split.repo.startsWith("ssh://")&&!split.repo.startsWith("git://")&&!split.repo.startsWith("git@");return buildGitSource({repo:useHttpsPrefix?`https://${split.repo}`:split.repo,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}let httpsCandidates=[split.ref?`https://${split.repo}#${split.ref}`:void 0,`https://${url}`].filter(value=>!!value);for(let candidate of httpsCandidates){let info=import_hosted_git_info.default.fromUrl(candidate);if(info){if(split.ref&&info.project?.includes("@"))continue;return buildGitSource({repo:`https://${split.repo}`,host:info.domain||"",path:`${info.user}/${info.project}`,ref:info.committish||split.ref||void 0})}}return parseGenericGitUrl(url)}function isExactNpmVersion(version){return(0,import_semver3.valid)(version??"")!==null}function getNpmVersionRange(version){return version?(0,import_semver3.validRange)(version)??void 0:void 0}function getHomeDir(){return process.env.HOME||homedir7()}function getBaseDirForScope(ctx,scope){return scope==="project"?join40(ctx.cwd,CONFIG_DIR_NAME):scope==="user"?ctx.agentDir:ctx.cwd}function resolvePath3(ctx,input){return resolvePath(input,ctx.cwd,{homeDir:getHomeDir(),trim:!0})}function resolvePathFromBase(input,baseDir){return resolvePath(input,baseDir,{homeDir:getHomeDir(),trim:!0})}function parseNpmSpec(spec){let match2=spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!match2)return{name:spec};let name=match2[1]??spec,version=match2[2];return{name,version}}function parseSource(source){if(source.startsWith("npm:")){let spec=source.slice(4).trim(),{name,version}=parseNpmSpec(spec);return{type:"npm",spec,name,version,range:getNpmVersionRange(version),pinned:isExactNpmVersion(version)}}if(isLocalPath(source))return{type:"local",path:source};let gitParsed=parseGitUrl(source);return gitParsed||{type:"local",path:source}}function getPackageSourceString(pkg2){return typeof pkg2=="string"?pkg2:pkg2.source}function getSourceMatchKeyForInput(ctx,source){let parsed=parseSource(source);return parsed.type==="npm"?`npm:${parsed.name}`:parsed.type==="git"?`git:${parsed.host}/${parsed.path}`:`local:${resolvePath3(ctx,parsed.path)}`}function getSourceMatchKeyForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}function buildNoMatchingPackageMessage(source,configuredPackages){let suggestion=findSuggestedConfiguredSource(source,configuredPackages);return suggestion?`No matching package found for ${source}. Did you mean ${suggestion}?`:`No matching package found for ${source}`}function findSuggestedConfiguredSource(source,configuredPackages){let trimmedSource=source.trim(),suggestions=new Set;for(let pkg2 of configuredPackages){let sourceStr=getPackageSourceString(pkg2),parsed=parseSource(sourceStr);if(parsed.type==="npm"){(trimmedSource===parsed.name||trimmedSource===parsed.spec)&&suggestions.add(sourceStr);continue}if(parsed.type==="git"){let shorthand=`${parsed.host}/${parsed.path}`,shorthandWithRef=parsed.ref?`${shorthand}@${parsed.ref}`:void 0;(trimmedSource===shorthand||shorthandWithRef&&trimmedSource===shorthandWithRef)&&suggestions.add(sourceStr)}}return suggestions.values().next().value}function normalizePackageSourceForSettings(ctx,source,scope){let parsed=parseSource(source);if(parsed.type!=="local")return source;let baseDir=getBaseDirForScope(ctx,scope),resolved=resolvePath3(ctx,parsed.path);return relative7(baseDir,resolved)||"."}function getPackageIdentity(ctx,source,scope){let parsed=parseSource(source);if(parsed.type==="npm")return`npm:${parsed.name}`;if(parsed.type==="git")return`git:${parsed.host}/${parsed.path}`;if(scope){let baseDir=getBaseDirForScope(ctx,scope);return`local:${resolvePathFromBase(parsed.path,baseDir)}`}return`local:${resolvePath3(ctx,parsed.path)}`}function dedupePackages(ctx,packages){let result=[],seen=new Map;for(let entry of packages){let identity=getPackageIdentity(ctx,getPackageSourceString(entry.pkg),entry.scope),index3=seen.get(identity);if(index3===void 0){seen.set(identity,result.length),result.push(entry);continue}let existing=result[index3];existing?.scope==="project"&&entry.scope==="user"?typeof existing.pkg=="object"&&existing.pkg.autoload===!1&&result.push(entry):entry.scope==="project"&&(result[index3]=entry)}return result}import{readFileSync as readFileSync15}from"node:fs";var RESOURCE_FIELDS=["skills","prompts","themes"];function isObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readPiManifest(packageJsonPath){try{let pkg2=JSON.parse(stripBom(readFileSync15(packageJsonPath,"utf-8")));if(!isObject4(pkg2)||!isObject4(pkg2.pi))return null;let manifest={};for(let field2 of RESOURCE_FIELDS){let entries=pkg2.pi[field2];Array.isArray(entries)&&entries.every(entry=>typeof entry=="string")&&(manifest[field2]=entries)}return manifest}catch{return null}}function resourcePrecedenceRank(m2){return m2.origin==="package"?4:(m2.scope==="project"?0:2)+(m2.source==="local"?0:1)}function collectPackageResources(packageRoot,accumulator,filter2,metadata){if(filter2){for(let resourceType of RESOURCE_TYPES){let patterns=filter2[resourceType],target=getTargetMap(accumulator,resourceType);filter2.autoload===!1?applyPackageDeltaFilter(packageRoot,patterns??[],resourceType,target,metadata):patterns!==void 0?applyPackageFilter(packageRoot,patterns,resourceType,target,metadata):collectDefaultResources(packageRoot,resourceType,target,metadata)}return!0}let manifest=readPiManifest(join41(packageRoot,"package.json"));if(manifest){for(let resourceType of RESOURCE_TYPES){let entries=manifest[resourceType];addManifestEntries(entries,packageRoot,resourceType,getTargetMap(accumulator,resourceType),metadata)}return!0}let hasAnyDir=!1;for(let resourceType of RESOURCE_TYPES){let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(getTargetMap(accumulator,resourceType),f,metadata,!0);hasAnyDir=!0}}return hasAnyDir}function collectDefaultResources(packageRoot,resourceType,target,metadata){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries){addManifestEntries(entries,packageRoot,resourceType,target,metadata);return}let dir=join41(packageRoot,resourceType);if(existsSync15(dir)){let files=collectResourceFiles(dir,resourceType);for(let f of files)addResource(target,f,metadata,!0)}}function applyPackageFilter(packageRoot,userPatterns,resourceType,target,metadata){let{allFiles}=collectManifestFiles(packageRoot,resourceType);if(userPatterns.length===0){for(let f of allFiles)addResource(target,f,metadata,!1);return}let enabledByUser=applyPatterns(allFiles,userPatterns,packageRoot);for(let f of allFiles){let enabled=enabledByUser.has(f);addResource(target,f,metadata,enabled)}}function applyPackageDeltaFilter(packageRoot,userPatterns,resourceType,target,metadata){if(userPatterns.length===0)return;let{allFiles}=collectManifestFiles(packageRoot,resourceType),enabledByUser=applyAutoloadDisabledPatterns(allFiles,userPatterns,packageRoot);for(let[filePath,enabled]of enabledByUser)addResource(target,filePath,metadata,enabled)}function collectManifestFiles(packageRoot,resourceType){let entries=readPiManifest(join41(packageRoot,"package.json"))?.[resourceType];if(entries&&entries.length>0){let allFiles2=collectFilesFromManifestEntries(entries,packageRoot,resourceType),manifestPatterns=entries.filter(isOverridePattern),enabledByManifest=manifestPatterns.length>0?applyPatterns(allFiles2,manifestPatterns,packageRoot):new Set(allFiles2);return{allFiles:Array.from(enabledByManifest),enabledByManifest}}let conventionDir=join41(packageRoot,resourceType);if(!existsSync15(conventionDir))return{allFiles:[],enabledByManifest:new Set};let allFiles=collectResourceFiles(conventionDir,resourceType);return{allFiles,enabledByManifest:new Set(allFiles)}}function addManifestEntries(entries,root,resourceType,target,metadata){if(!entries)return;let allFiles=collectFilesFromManifestEntries(entries,root,resourceType),patterns=entries.filter(isOverridePattern),enabledPaths=applyPatterns(allFiles,patterns,root);for(let f of allFiles)enabledPaths.has(f)&&addResource(target,f,metadata,!0)}function collectFilesFromManifestEntries(entries,root,resourceType){let resolved=entries.filter(entry=>!isOverridePattern(entry)).flatMap(entry=>hasGlobPattern(entry)?expandPackageGlob(entry,root):[resolve14(root,entry)]);return collectFilesFromPaths(resolved,resourceType)}function resolveLocalEntries(entries,resourceType,target,metadata,baseDir){if(entries.length===0)return;let{plain,patterns}=splitPatterns(entries),resolvedPlain=plain.map(p=>resolvePathFromBase(p,baseDir)),allFiles=collectFilesFromPaths(resolvedPlain,resourceType),enabledPaths=applyPatterns(allFiles,patterns,baseDir);for(let f of allFiles)addResource(target,f,metadata,enabledPaths.has(f))}function addAutoDiscoveredResources(cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir){let userMetadata={source:"auto",scope:"user",origin:"top-level",baseDir:globalBaseDir},projectMetadata={source:"auto",scope:"project",origin:"top-level",baseDir:projectBaseDir},userOverrides={skills:globalSettings.skills??[],prompts:globalSettings.prompts??[],themes:globalSettings.themes??[]},projectOverrides={skills:projectSettings.skills??[],prompts:projectSettings.prompts??[],themes:projectSettings.themes??[]},userDirs={skills:join41(globalBaseDir,"skills"),prompts:join41(globalBaseDir,"prompts"),themes:join41(globalBaseDir,"themes")},projectDirs={skills:join41(projectBaseDir,"skills"),prompts:join41(projectBaseDir,"prompts"),themes:join41(projectBaseDir,"themes")},userAgentsSkillsDir=join41(getHomeDir(),".agents","skills"),projectAgentsSkillDirs=collectAncestorAgentsSkillDirs(cwd).filter(dir=>resolve14(dir)!==resolve14(userAgentsSkillsDir)),addResources=(resourceType,paths,metadata,overrides,baseDir)=>{let target=getTargetMap(accumulator,resourceType);for(let path15 of paths){let enabled=isEnabledByOverrides(path15,overrides,baseDir);addResource(target,path15,metadata,enabled)}};addResources("skills",collectAutoSkillEntries(projectDirs.skills,"project"),projectMetadata,projectOverrides.skills,projectBaseDir);for(let agentsSkillsDir of projectAgentsSkillDirs){let agentsBaseDir=dirname22(agentsSkillsDir),agentsMetadata={...projectMetadata,baseDir:agentsBaseDir};addResources("skills",collectAutoSkillEntries(agentsSkillsDir,"agents"),agentsMetadata,projectOverrides.skills,agentsBaseDir)}addResources("prompts",collectAutoPromptEntries(projectDirs.prompts),projectMetadata,projectOverrides.prompts,projectBaseDir),addResources("themes",collectAutoThemeEntries(projectDirs.themes),projectMetadata,projectOverrides.themes,projectBaseDir),addResources("skills",collectAutoSkillEntries(userDirs.skills,"project"),userMetadata,userOverrides.skills,globalBaseDir);let userAgentsBaseDir=dirname22(userAgentsSkillsDir),userAgentsMetadata={...userMetadata,baseDir:userAgentsBaseDir};addResources("skills",collectAutoSkillEntries(userAgentsSkillsDir,"agents"),userAgentsMetadata,userOverrides.skills,userAgentsBaseDir),addResources("prompts",collectAutoPromptEntries(userDirs.prompts),userMetadata,userOverrides.prompts,globalBaseDir),addResources("themes",collectAutoThemeEntries(userDirs.themes),userMetadata,userOverrides.themes,globalBaseDir)}function collectFilesFromPaths(paths,resourceType){let files=[];for(let p of paths)if(existsSync15(p))try{let stats=statSync12(p);stats.isFile()?files.push(p):stats.isDirectory()&&files.push(...collectResourceFiles(p,resourceType))}catch{}return files}function getTargetMap(accumulator,resourceType){switch(resourceType){case"skills":return accumulator.skills;case"prompts":return accumulator.prompts;case"themes":return accumulator.themes;default:throw new Error(`Unknown resource type: ${resourceType}`)}}function addResource(map,path15,metadata,enabled){path15&&(map.has(path15)||map.set(path15,{metadata,enabled}))}function createAccumulator(){return{skills:new Map,prompts:new Map,themes:new Map}}function toResolvedPaths(accumulator){let mapToResolved=entries=>{let resolved=Array.from(entries.entries()).map(([path15,{metadata,enabled}])=>({path:path15,enabled,metadata}));resolved.sort((a,b2)=>resourcePrecedenceRank(a.metadata)-resourcePrecedenceRank(b2.metadata));let seen=new Set;return resolved.filter(entry=>{let canonicalPath=canonicalizePath(entry.path);return seen.has(canonicalPath)?!1:(seen.add(canonicalPath),!0)})};return{skills:mapToResolved(accumulator.skills),prompts:mapToResolved(accumulator.prompts),themes:mapToResolved(accumulator.themes)}}var NETWORK_TIMEOUT_MS2=1e4,UPDATE_CHECK_CONCURRENCY=4,GIT_UPDATE_CONCURRENCY=4,DefaultPackageManager=class{cwd;agentDir;settingsManager;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(options){this.cwd=resolvePath(options.cwd),this.agentDir=resolvePath(options.agentDir),this.settingsManager=options.settingsManager}get context(){return{cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}}setProgressCallback(callback){this.progressCallback=callback}addSourceToSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],normalizedSource=this.normalizePackageSourceForSettings(source,scope),matchIndex=currentPackages.findIndex(existing=>this.packageSourcesMatch(existing,source,scope));if(matchIndex!==-1){let existing=currentPackages[matchIndex];if(this.getPackageSourceString(existing)===normalizedSource)return!1;let nextPackages2=[...currentPackages];return nextPackages2[matchIndex]=typeof existing=="string"?normalizedSource:{...existing,source:normalizedSource},scope==="project"?this.settingsManager.setProjectPackages(nextPackages2):this.settingsManager.setPackages(nextPackages2),!0}let nextPackages=[...currentPackages,normalizedSource];return scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0}removeSourceFromSettings(source,options){let scope=options?.local?"project":"user",currentPackages=(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],nextPackages=currentPackages.filter(existing=>!this.packageSourcesMatch(existing,source,scope));return nextPackages.length!==currentPackages.length?(scope==="project"?this.settingsManager.setProjectPackages(nextPackages):this.settingsManager.setPackages(nextPackages),!0):!1}getInstalledPath(source,scope){let parsed=this.parseSource(source);if(parsed.type==="npm"){let path15=this.getNpmInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="git"){let path15=this.getGitInstallPath(parsed,scope);return existsSync16(path15)?path15:void 0}if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(scope),path15=this.resolvePathFromBase(parsed.path,baseDir);return existsSync16(path15)?path15:void 0}}emitProgress(event){this.progressCallback?.(event)}async withProgress(action,source,message,operation){this.emitProgress({type:"start",action,source,message});try{await operation(),this.emitProgress({type:"complete",action,source})}catch(error2){let errorMessage2=error2 instanceof Error?error2.message:String(error2);throw this.emitProgress({type:"error",action,source,message:errorMessage2}),error2}}async resolve(onMissing){let accumulator=createAccumulator(),globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let packageSources=this.dedupePackages(allPackages);await this.resolvePackageSources(packageSources,accumulator,onMissing);let globalBaseDir=this.agentDir,projectBaseDir=join42(this.cwd,CONFIG_DIR_NAME);for(let resourceType of RESOURCE_TYPES){let target=getTargetMap(accumulator,resourceType),globalEntries=globalSettings[resourceType]??[],projectEntries=projectSettings[resourceType]??[];resolveLocalEntries(projectEntries,resourceType,target,{source:"local",scope:"project",origin:"top-level"},projectBaseDir),resolveLocalEntries(globalEntries,resourceType,target,{source:"local",scope:"user",origin:"top-level"},globalBaseDir)}return addAutoDiscoveredResources(this.cwd,accumulator,globalSettings,projectSettings,globalBaseDir,projectBaseDir),toResolvedPaths(accumulator)}async resolveSourceResources(sources,options){let accumulator=createAccumulator(),scope=options?.temporary?"temporary":options?.local?"project":"user",packageSources=sources.map(source=>({pkg:source,scope}));return await this.resolvePackageSources(packageSources,accumulator),toResolvedPaths(accumulator)}listConfiguredPackages(){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),configuredPackages=[];for(let pkg2 of globalSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"user",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"user")})}for(let pkg2 of projectSettings.packages??[]){let source=typeof pkg2=="string"?pkg2:pkg2.source;configuredPackages.push({source,scope:"project",filtered:typeof pkg2=="object",installedPath:this.getInstalledPath(source,"project")})}return configuredPackages}async install(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("install",source,`Installing ${source}...`,async()=>{if(parsed.type==="npm"){await this.installNpm(parsed,scope,!1);return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}if(parsed.type==="local"){let resolved=this.resolvePath(parsed.path);if(!existsSync16(resolved))throw new Error(`Path does not exist: ${resolved}`);return}throw new Error(`Unsupported install source: ${source}`)})}async installAndPersist(source,options){await this.install(source,options),this.addSourceToSettings(source,options)}async remove(source,options){let parsed=this.parseSource(source),scope=options?.local?"project":"user";await this.withProgress("remove",source,`Removing ${source}...`,async()=>{if(parsed.type==="npm"){await this.uninstallNpm(parsed,scope);return}if(parsed.type==="git"){await this.removeGit(parsed,scope);return}if(parsed.type!=="local")throw new Error(`Unsupported remove source: ${source}`)})}async removeAndPersist(source,options){return await this.remove(source,options),this.removeSourceFromSettings(source,options)}async update(source){let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),identity=source?this.getPackageIdentity(source):void 0,matched=!1,updateSources=[];for(let pkg2 of globalSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"user")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"user"}))}for(let pkg2 of projectSettings.packages??[]){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source;identity&&this.getPackageIdentity(sourceStr,"project")!==identity||(matched=!0,updateSources.push({source:sourceStr,scope:"project"}))}if(source&&!matched)throw new Error(this.buildNoMatchingPackageMessage(source,[...globalSettings.packages??[],...projectSettings.packages??[]]));await this.updateConfiguredSources(updateSources)}async updateConfiguredSources(sources){if(isOfflineModeEnabled2()||sources.length===0)return;let npmCandidates=[],gitCandidates=[];for(let entry of sources){let parsed=this.parseSource(entry.source);parsed.type==="npm"?parsed.pinned||npmCandidates.push({...entry,parsed}):parsed.type==="git"&&gitCandidates.push({...entry,parsed})}let npmCheckTasks=npmCandidates.map(entry=>async()=>({entry,shouldUpdate:await this.shouldUpdateNpmSource(entry.parsed,entry.scope)})),npmCheckResults=await runWithConcurrency(npmCheckTasks,UPDATE_CHECK_CONCURRENCY),userNpmUpdates=[],projectNpmUpdates=[];for(let result of npmCheckResults)result.shouldUpdate&&(result.entry.scope==="user"?userNpmUpdates.push(result.entry):projectNpmUpdates.push(result.entry));let tasks=[];if(userNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(userNpmUpdates,"user")),projectNpmUpdates.length>0&&tasks.push(this.updateNpmBatch(projectNpmUpdates,"project")),gitCandidates.length>0){let gitTasks=gitCandidates.map(entry=>async()=>this.withProgress("update",entry.source,`Updating ${entry.source}...`,async()=>{await this.updateGit(entry.parsed,entry.scope)}));tasks.push(runWithConcurrency(gitTasks,GIT_UPDATE_CONCURRENCY).then(()=>{}))}await Promise.all(tasks)}async shouldUpdateNpmSource(source,scope){let installedPath=getManagedNpmInstallPath(this.context,source,scope),installedVersion=existsSync16(installedPath)?this.getInstalledNpmVersion(installedPath):void 0;if(!installedVersion)return!0;let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}async updateNpmBatch(sources,scope){if(sources.length===0)return;let sourceLabel=sources.length===1?sources[0].source:`${scope} npm packages`,message=sources.length===1?`Updating ${sources[0].source}...`:`Updating ${scope} npm packages...`,specs=sources.map(entry=>entry.parsed.version?entry.parsed.spec:`${entry.parsed.name}@latest`);await this.withProgress("update",sourceLabel,message,async()=>{await this.installNpmBatch(specs,scope)})}async installNpmBatch(specs,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,specs,installRoot))}async checkForAvailableUpdates(){if(isOfflineModeEnabled2())return[];let globalSettings=this.settingsManager.getGlobalSettings(),projectSettings=this.settingsManager.getProjectSettings(),allPackages=[];for(let pkg2 of projectSettings.packages??[])allPackages.push({pkg:pkg2,scope:"project"});for(let pkg2 of globalSettings.packages??[])allPackages.push({pkg:pkg2,scope:"user"});let checks=this.dedupePackages(allPackages).filter(entry=>entry.scope!=="temporary").map(entry=>async()=>{let source=typeof entry.pkg=="string"?entry.pkg:entry.pkg.source,parsed=this.parseSource(source);if(parsed.type==="local"||parsed.pinned)return;if(parsed.type==="npm"){let installedPath2=this.getNpmInstallPath(parsed,entry.scope);return!existsSync16(installedPath2)||!await this.npmHasAvailableUpdate(parsed,installedPath2)?void 0:{source,displayName:parsed.name,type:"npm",scope:entry.scope}}let installedPath=this.getGitInstallPath(parsed,entry.scope);if(!(!existsSync16(installedPath)||!await this.gitHasAvailableUpdate(installedPath)))return{source,displayName:`${parsed.host}/${parsed.path}`,type:"git",scope:entry.scope}});return(await runWithConcurrency(checks,UPDATE_CHECK_CONCURRENCY)).filter(result=>result!==void 0)}async resolvePackageSources(sources,accumulator,onMissing){for(let{pkg:pkg2,scope}of sources){let sourceStr=typeof pkg2=="string"?pkg2:pkg2.source,filter2=typeof pkg2=="object"?pkg2:void 0,deltaBase=this.findAutoloadDeltaBase(pkg2,scope,sources),resolvedSource=deltaBase?.source??sourceStr,resolvedScope=deltaBase?.scope??scope,parsed=this.parseSource(resolvedSource),metadata={source:sourceStr,scope,origin:"package"};if(parsed.type==="local"){let baseDir=this.getBaseDirForScope(resolvedScope),resolvedLocal=this.resolvePathFromBase(parsed.path,baseDir);if(existsSync16(resolvedLocal))try{statSync13(resolvedLocal).isDirectory()&&(metadata.baseDir=resolvedLocal,collectPackageResources(resolvedLocal,accumulator,filter2,metadata))}catch{}continue}let installMissing=async()=>{if(isOfflineModeEnabled2())return!1;if(!onMissing)return await this.installParsedSource(parsed,resolvedScope),!0;let action=await onMissing(resolvedSource);if(action==="skip")return!1;if(action==="error")throw new Error(`Missing source: ${resolvedSource}`);return await this.installParsedSource(parsed,resolvedScope),!0};if(parsed.type==="npm"){let installedPath=this.getNpmInstallPath(parsed,resolvedScope);if(!existsSync16(installedPath)||!await installedNpmMatchesConfiguredVersion(parsed,installedPath)){if(!await installMissing())continue;installedPath=this.getNpmInstallPath(parsed,resolvedScope)}metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata);continue}if(parsed.type==="git"){let installedPath=this.getGitInstallPath(parsed,resolvedScope);if(existsSync16(installedPath))resolvedScope==="temporary"&&!parsed.pinned&&!isOfflineModeEnabled2()&&await this.refreshTemporaryGitSource(parsed,resolvedSource);else if(!await installMissing())continue;metadata.baseDir=installedPath,collectPackageResources(installedPath,accumulator,filter2,metadata)}}}findAutoloadDeltaBase(pkg2,scope,sources){if(scope!=="project"||typeof pkg2!="object"||pkg2.autoload!==!1)return;let identity=this.getPackageIdentity(pkg2.source,scope),userEntry=sources.find(entry=>entry.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(entry.pkg),"user")===identity);return userEntry?{source:this.getPackageSourceString(userEntry.pkg),scope:"user"}:void 0}async installParsedSource(parsed,scope){if(parsed.type==="npm"){await this.installNpm(parsed,scope,scope==="temporary");return}if(parsed.type==="git"){await this.installGit(parsed,scope);return}}parseSource(source){return parseSource(source)}getBaseDirForScope(scope){return getBaseDirForScope(this.context,scope)}resolvePath(input){return resolvePath3(this.context,input)}resolvePathFromBase(input,baseDir){return resolvePathFromBase(input,baseDir)}getPackageSourceString(pkg2){return getPackageSourceString(pkg2)}getSourceMatchKeyForInput(source){return getSourceMatchKeyForInput(this.context,source)}getSourceMatchKeyForSettings(source,scope){return getSourceMatchKeyForSettings(this.context,source,scope)}packageSourcesMatch(existing,inputSource,scope){let left=this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing),scope),right=this.getSourceMatchKeyForInput(inputSource);return left===right}normalizePackageSourceForSettings(source,scope){return normalizePackageSourceForSettings(this.context,source,scope)}getPackageIdentity(source,scope){return getPackageIdentity(this.context,source,scope)}dedupePackages(packages){return dedupePackages(this.context,packages)}buildNoMatchingPackageMessage(source,configuredPackages){return buildNoMatchingPackageMessage(source,configuredPackages)}getNpmCommand(){return getNpmCommand(this.context)}getInstalledNpmVersion(installedPath){return getInstalledNpmVersion(installedPath)}getGitInstallPath(source,scope){return getGitInstallPath(this.context,source,scope)}async npmHasAvailableUpdate(source,installedPath){if(isOfflineModeEnabled2())return!1;let installedVersion=this.getInstalledNpmVersion(installedPath);if(!installedVersion)return!1;try{let targetVersion=await this.getLatestNpmVersion(source.version?source.spec:source.name,source.range);return(0,import_semver4.gt)(targetVersion,installedVersion)}catch{return!1}}async getLatestNpmVersion(packageSpec,range2){let npmCommand=this.getNpmCommand(),raw=(await this.runCommandCapture(npmCommand.command,[...npmCommand.args,"view",packageSpec,"version","--json"],{cwd:this.cwd,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!raw)throw new Error("Empty response from npm view");let parsed=JSON.parse(raw);if(typeof parsed=="string")return parsed;if(Array.isArray(parsed)){let versions=parsed.filter(value=>typeof value=="string"&&value.length>0),latest=range2?(0,import_semver4.maxSatisfying)(versions,range2):[...versions].sort(import_semver4.rcompare)[0];if(latest)return latest}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(installedPath){if(isOfflineModeEnabled2())return!1;try{let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),remoteHead=await this.getRemoteGitHead(installedPath);return localHead.trim()!==remoteHead.trim()}catch{return!1}}async getRemoteGitHead(installedPath){let upstreamRef=await this.getGitUpstreamRef(installedPath);if(upstreamRef){let match3=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin",upstreamRef])).match(/^([0-9a-f]{40})\s+/m);if(match3?.[1])return match3[1]}let match2=(await this.runGitRemoteCommand(installedPath,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!match2?.[1])throw new Error("Failed to determine remote HEAD");return match2[1]}async getLocalGitUpdateTarget(installedPath){try{let trimmedUpstream=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmedUpstream.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`);let branch=trimmedUpstream.slice(7);if(!branch)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:installedPath}).catch(()=>{});let head=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}),branch=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return branch?{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${branch}:refs/remotes/origin/${branch}`]}:{ref:"origin/HEAD",head,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(installedPath){try{let trimmed=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2})).trim();if(!trimmed.startsWith("origin/"))return;let branch=trimmed.slice(7);return branch?`refs/heads/${branch}`:void 0}catch{return}}runGitRemoteCommand(installedPath,args){return this.runCommandCapture("git",args,{cwd:installedPath,timeoutMs:NETWORK_TIMEOUT_MS2,env:{GIT_TERMINAL_PROMPT:"0"}})}getGlobalNpmRoot(){let npmCommand=this.getNpmCommand(),commandKey=[npmCommand.command,...npmCommand.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===commandKey)return this.globalNpmRoot;if(getPackageManagerName(this.context)==="bun"){let binDir=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=join42(dirname23(binDir),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=commandKey,this.globalNpmRoot}getPnpmGlobalPackagePath(packageName){if(getPackageManagerName(this.context)!=="pnpm")return;let output=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),entries=JSON.parse(output);for(let entry of entries){let path15=entry.dependencies?.[packageName]?.path;if(path15)return path15}}getLegacyGlobalNpmInstallPath(source){try{return this.getPnpmGlobalPackagePath(source.name)??join42(this.getGlobalNpmRoot(),source.name)}catch{return}}getNpmInstallPath(source,scope){let managedPath=getManagedNpmInstallPath(this.context,source,scope);if(scope!=="user"||existsSync16(managedPath))return managedPath;let legacyPath=this.getLegacyGlobalNpmInstallPath(source);return legacyPath&&existsSync16(legacyPath)?legacyPath:managedPath}async installNpm(source,scope,temporary){let installRoot=getNpmInstallRoot(this.context,scope,temporary);ensureNpmProject(installRoot),await this.runNpmCommand(getNpmInstallArgs(this.context,[source.spec],installRoot))}async uninstallNpm(source,scope){let installRoot=getNpmInstallRoot(this.context,scope,!1);if(!existsSync16(installRoot))return;let packageManagerName=getPackageManagerName(this.context);if(packageManagerName==="bun"){await this.runNpmCommand(["uninstall",source.name,"--cwd",installRoot]);return}let args=["uninstall",source.name,"--prefix",installRoot];packageManagerName!=="pnpm"&&args.push("--legacy-peer-deps"),await this.runNpmCommand(args)}async installGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(existsSync16(targetDir)){if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref);return}let gitRoot=getGitInstallRoot(this.context,scope);gitRoot&&ensureGitIgnore(gitRoot),mkdirSync11(dirname23(targetDir),{recursive:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0});try{await this.runCommand("git",["clone",source.repo,targetDir]),source.ref&&await this.runCommand("git",["checkout",source.ref],{cwd:targetDir});let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}catch(error2){throw rmSync4(targetDir,{recursive:!0,force:!0}),pruneEmptyGitParents(targetDir,gitRoot),error2}}async updateGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);if(!existsSync16(targetDir)){await this.installGit(source,scope);return}if(source.ref){await this.ensureGitRef(targetDir,["fetch","origin",source.ref],"FETCH_HEAD");return}let target=await this.getLocalGitUpdateTarget(targetDir);await this.ensureGitRef(targetDir,target.fetchArgs,target.ref)}async repairMissingGitDependencies(targetDir){hasMissingGitDependencies(targetDir)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir})}async cleanAndInstallGitDependencies(targetDir,markerPath){try{await this.runCommand("git",["clean","-fdx"],{cwd:targetDir})}catch(error2){throw await this.repairMissingGitDependencies(targetDir).catch(()=>{}),error2}let packageJsonPath=join42(targetDir,"package.json");existsSync16(packageJsonPath)&&await this.runNpmCommand(getGitDependencyInstallArgs(this.context),{cwd:targetDir}),rmSync4(markerPath,{force:!0})}async ensureGitRef(targetDir,fetchArgs,ref){await this.runCommand("git",fetchArgs,{cwd:targetDir});let localHead=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),commitRef=`${ref}^{commit}`,targetHead=await this.runCommandCapture("git",["rev-parse",commitRef],{cwd:targetDir,timeoutMs:NETWORK_TIMEOUT_MS2}),markerPath=getGitUpdateMarkerPath(targetDir);if(localHead.trim()===targetHead.trim()){existsSync16(markerPath)?await this.cleanAndInstallGitDependencies(targetDir,markerPath):await this.repairMissingGitDependencies(targetDir);return}writeFileSync10(markerPath,"","utf-8"),await this.runCommand("git",["reset","--hard",commitRef],{cwd:targetDir}),await this.cleanAndInstallGitDependencies(targetDir,markerPath)}async refreshTemporaryGitSource(source,sourceStr){if(!isOfflineModeEnabled2())try{await this.withProgress("pull",sourceStr,`Refreshing ${sourceStr}...`,async()=>{await this.updateGit(source,"temporary")})}catch{}}async removeGit(source,scope){let targetDir=this.getGitInstallPath(source,scope);rmSync4(targetDir,{recursive:!0,force:!0}),rmSync4(getGitUpdateMarkerPath(targetDir),{force:!0}),pruneEmptyGitParents(targetDir,getGitInstallRoot(this.context,scope))}async runNpmCommand(args,options){let npmCommand=this.getNpmCommand();await this.runCommand(npmCommand.command,[...npmCommand.args,...args],options)}runNpmCommandSync(args){let npmCommand=this.getNpmCommand();return this.runCommandSync(npmCommand.command,[...npmCommand.args,...args])}spawnCommand(command,args,options){let env2=getEnv();return spawnProcess(command,args,{cwd:options?.cwd,stdio:isStdoutTakenOver()?["ignore",2,2]:"inherit",env:env2})}spawnCaptureCommand(command,args,options){let baseEnv=getEnv(),env2=options?.env?{...baseEnv,...options.env}:baseEnv;return spawnProcess(command,args,{cwd:options?.cwd,stdio:["ignore","pipe","pipe"],env:env2})}runCommandCapture(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCaptureCommand(command,args,options),stdout="",stderr="",timedOut=!1,timeout=typeof options?.timeoutMs=="number"?setTimeout(()=>{timedOut=!0,child.kill()},options.timeoutMs):void 0;child.stdout?.on("data",data=>{stdout+=data.toString()}),child.stderr?.on("data",data=>{stderr+=data.toString()}),child.once("error",error2=>{timeout&&clearTimeout(timeout),reject2(error2)}),child.once("close",(code,signal)=>{if(timeout&&clearTimeout(timeout),timedOut){reject2(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));return}if(code===0){resolvePromise(stdout.trim());return}let exitStatus=code===null?`signal ${signal??"unknown"}`:`code ${code}`;reject2(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr||stdout}`))})})}runCommand(command,args,options){return new Promise((resolvePromise,reject2)=>{let child=this.spawnCommand(command,args,options);child.on("error",reject2),child.on("exit",code=>{code===0?resolvePromise():reject2(new Error(`${command} ${args.join(" ")} failed with code ${code}`))})})}runCommandSync(command,args){let env2=getEnv(),result=spawnProcessSync(command,args,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:env2});if(result.error||result.status!==0)throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message||result.stderr||result.stdout}`);return(result.stdout||result.stderr||"").trim()}};var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{randomUUID as randomUUID15}from"crypto";import{existsSync as existsSync17,mkdirSync as mkdirSync12,readFileSync as readFileSync16,writeFileSync as writeFileSync11}from"fs";import{dirname as dirname24,join as join43}from"path";function isMergeableObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function deepMergeObjects(base,overrides){let result={...base};for(let key of Object.keys(overrides)){let overrideValue=overrides[key];if(overrideValue===void 0)continue;let baseValue=base[key];result[key]=isMergeableObject(baseValue)&&isMergeableObject(overrideValue)?deepMergeObjects(baseValue,overrideValue):overrideValue}return result}function deepMergeSettings(base,overrides){return deepMergeObjects(base,overrides)}function parseTimeoutSetting(value,settingName){let timeoutMs=parseHttpIdleTimeoutMs(value);if(timeoutMs!==void 0)return timeoutMs;if(value!==void 0)throw new Error(`Invalid ${settingName} setting: ${String(value)}`)}function toSettingsError(scope,error2,path15){return{scope,...path15?{path:path15}:{},error:error2 instanceof Error?error2:new Error(String(error2))}}var FileSettingsStorage=class{globalSettingsPath;projectSettingsPath;constructor(cwd,agentDir){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir);this.globalSettingsPath=join43(resolvedAgentDir,"settings.json"),this.projectSettingsPath=join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")}acquireLockSyncWithRetry(path15){let lastError;for(let attempt2=1;attempt2<=10;attempt2++)try{return import_proper_lockfile2.default.lockSync(path15,{realpath:!1})}catch(error2){if((typeof error2=="object"&&error2!==null&&"code"in error2?String(error2.code):void 0)!=="ELOCKED"||attempt2===10)throw error2;lastError=error2;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire settings lock")}withLock(scope,fn){let path15=scope==="global"?this.globalSettingsPath:this.projectSettingsPath,dir=dirname24(path15),release;try{let fileExists2=existsSync17(path15);fileExists2&&(release=this.acquireLockSyncWithRetry(path15));let current=fileExists2?readFileSync16(path15,"utf-8"):void 0,next=fn(current);next!==void 0&&(existsSync17(dir)||mkdirSync12(dir,{recursive:!0}),release||(release=this.acquireLockSyncWithRetry(path15)),writeFileSync11(path15,next,"utf-8"))}finally{release&&release()}}},InMemorySettingsStorage=class{global;project;withLock(scope,fn){let current=scope==="global"?this.global:this.project,next=fn(current);next!==void 0&&(scope==="global"?this.global=next:this.project=next)}},SettingsManager=class _SettingsManager{storage;globalSettings;projectSettings;settings;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(storage,initialGlobal,initialProject,globalLoadError=null,projectLoadError=null,initialErrors=[],settingsPaths={}){this.storage=storage,this.globalSettings=initialGlobal,this.projectSettings=initialProject,this.globalSettingsLoadError=globalLoadError,this.projectSettingsLoadError=projectLoadError,this.errors=[...initialErrors],this.settingsPaths=settingsPaths,this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}static create(cwd,agentDir=getAgentDir(),options={}){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),storage=new FileSettingsStorage(resolvedCwd,resolvedAgentDir);return _SettingsManager.fromStorageWithPaths(storage,options,{global:join43(resolvedAgentDir,"settings.json"),project:join43(resolvedCwd,CONFIG_DIR_NAME,"settings.json")})}static fromStorage(storage,options={}){return _SettingsManager.fromStorageWithPaths(storage,options)}static fromStorageWithPaths(storage,options,settingsPaths={}){let globalLoad=_SettingsManager.tryLoadFromStorage(storage,"global"),projectLoad=_SettingsManager.tryLoadFromStorage(storage,"project"),initialErrors=[];return globalLoad.error&&initialErrors.push(toSettingsError("global",globalLoad.error,settingsPaths.global)),projectLoad.error&&initialErrors.push(toSettingsError("project",projectLoad.error,settingsPaths.project)),new _SettingsManager(storage,globalLoad.settings,projectLoad.settings,globalLoad.error,projectLoad.error,initialErrors,settingsPaths)}static inMemory(settings2={},options={}){let storage=new InMemorySettingsStorage,initialSettings=_SettingsManager.migrateSettings(structuredClone(settings2));return storage.withLock("global",()=>JSON.stringify(initialSettings,null,2)),_SettingsManager.fromStorage(storage,options)}static loadFromStorage(storage,scope){let content;if(storage.withLock(scope,current=>{content=current}),!content)return{};let settings2=JSON.parse(stripBom(content));return _SettingsManager.migrateSettings(settings2)}static tryLoadFromStorage(storage,scope){try{return{settings:_SettingsManager.loadFromStorage(storage,scope),error:null}}catch(error2){return{settings:{},error:error2}}}static migrateSettings(settings2){if("queueMode"in settings2&&!("steeringMode"in settings2)&&(settings2.steeringMode=settings2.queueMode,delete settings2.queueMode),!("transport"in settings2)&&typeof settings2.websockets=="boolean"&&(settings2.transport=settings2.websockets?"websocket":"sse",delete settings2.websockets),"skills"in settings2&&typeof settings2.skills=="object"&&settings2.skills!==null&&!Array.isArray(settings2.skills)){let skillsSettings=settings2.skills;skillsSettings.enableSkillCommands!==void 0&&settings2.enableSkillCommands===void 0&&(settings2.enableSkillCommands=skillsSettings.enableSkillCommands),Array.isArray(skillsSettings.customDirectories)&&skillsSettings.customDirectories.length>0?settings2.skills=skillsSettings.customDirectories:delete settings2.skills}if("retry"in settings2&&typeof settings2.retry=="object"&&settings2.retry!==null&&!Array.isArray(settings2.retry)){let retrySettings=settings2.retry,providerSettings=typeof retrySettings.provider=="object"&&retrySettings.provider!==null?retrySettings.provider:void 0;typeof retrySettings.maxDelayMs=="number"&&(providerSettings?.maxRetryDelayMs===void 0||providerSettings?.maxRetryDelayMs===null)&&(retrySettings.provider={...providerSettings??{},maxRetryDelayMs:retrySettings.maxDelayMs}),delete retrySettings.maxDelayMs}return settings2}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}async reload(){await this.writeQueue;let globalLoad=_SettingsManager.tryLoadFromStorage(this.storage,"global");globalLoad.error?(this.globalSettingsLoadError=globalLoad.error,this.recordError("global",globalLoad.error)):(this.globalSettings=globalLoad.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();let projectLoad=_SettingsManager.tryLoadFromStorage(this.storage,"project");projectLoad.error?(this.projectSettingsLoadError=projectLoad.error,this.recordError("project",projectLoad.error)):(this.projectSettings=projectLoad.settings,this.projectSettingsLoadError=null),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings)}applyOverrides(overrides){this.settings=deepMergeSettings(this.settings,overrides)}markModified(field2,nestedKey){this.modifiedFields.add(field2),nestedKey&&(this.modifiedNestedFields.has(field2)||this.modifiedNestedFields.set(field2,new Set),this.modifiedNestedFields.get(field2).add(nestedKey))}markProjectModified(field2,nestedKey){this.modifiedProjectFields.add(field2),nestedKey&&(this.modifiedProjectNestedFields.has(field2)||this.modifiedProjectNestedFields.set(field2,new Set),this.modifiedProjectNestedFields.get(field2).add(nestedKey))}recordError(scope,error2){this.errors.push(toSettingsError(scope,error2,this.settingsPaths[scope]))}clearModifiedScope(scope){if(scope==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(scope,task){this.writeQueue=this.writeQueue.then(()=>{task(),this.clearModifiedScope(scope)}).catch(error2=>{this.recordError(scope,error2)})}cloneModifiedNestedFields(source){let snapshot2=new Map;for(let[key,value]of source.entries())snapshot2.set(key,new Set(value));return snapshot2}persistScopedSettings(scope,snapshotSettings,modifiedFields,modifiedNestedFields){this.storage.withLock(scope,current=>{let currentFileSettings=current?_SettingsManager.migrateSettings(JSON.parse(stripBom(current))):{},mergedSettings={...currentFileSettings};for(let field2 of modifiedFields){let value=snapshotSettings[field2];if(modifiedNestedFields.has(field2)&&typeof value=="object"&&value!==null){let nestedModified=modifiedNestedFields.get(field2),baseNested=currentFileSettings[field2]??{},inMemoryNested=value,mergedNested={...baseNested};for(let nestedKey of nestedModified)mergedNested[nestedKey]=inMemoryNested[nestedKey];mergedSettings[field2]=mergedNested}else mergedSettings[field2]=value}return JSON.stringify(mergedSettings,null,2)})}save(){if(this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;let snapshotGlobalSettings=structuredClone(this.globalSettings),modifiedFields=new Set(this.modifiedFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",snapshotGlobalSettings,modifiedFields,modifiedNestedFields)})}saveProjectSettings(settings2){if(this.projectSettings=structuredClone(settings2),this.settings=deepMergeSettings(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;let snapshotProjectSettings=structuredClone(this.projectSettings),modifiedFields=new Set(this.modifiedProjectFields),modifiedNestedFields=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",snapshotProjectSettings,modifiedFields,modifiedNestedFields)})}updateProjectSettings(field2,update){let projectSettings=structuredClone(this.projectSettings);update(projectSettings),this.markProjectModified(field2),this.saveProjectSettings(projectSettings)}async flush(){await this.writeQueue}drainErrors(){let drained=[...this.errors];return this.errors=[],drained}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(version){this.globalSettings.lastChangelogVersion=version,this.markModified("lastChangelogVersion"),this.save()}getSuiteNoticeAcknowledgement(suiteId){return this.settings.suiteNoticesAcknowledged?.[suiteId]}setSuiteNoticeAcknowledgement(suiteId,ack){let next={...this.globalSettings.suiteNoticesAcknowledged??{},...this.settings.suiteNoticesAcknowledged??{}},existing=next[suiteId];next[suiteId]={...typeof existing=="object"&&existing!==null?existing:{},...ack.driftDigest===void 0?{}:{driftDigest:ack.driftDigest},...ack.upgradeRevision===void 0?{}:{upgradeRevision:ack.upgradeRevision}},this.globalSettings.suiteNoticesAcknowledged=next,this.settings.suiteNoticesAcknowledged=next,this.markModified("suiteNoticesAcknowledged"),this.save()}getSessionDir(){let sessionDir=this.settings.sessionDir;return sessionDir&&normalizePath(sessionDir)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}getMemoryModeSetting(){return this.settings.memory?.mode}setDefaultProvider(provider){this.globalSettings.defaultProvider=provider,this.markModified("defaultProvider"),this.save()}setDefaultModel(modelId){this.globalSettings.defaultModel=modelId,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(provider,modelId){this.globalSettings.defaultProvider=provider,this.globalSettings.defaultModel=modelId,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(mode){this.globalSettings.steeringMode=mode,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(mode){this.globalSettings.followUpMode=mode,this.markModified("followUpMode"),this.save()}getThemeSetting(){let value=this.settings.theme;if(typeof value=="string")return value}getTheme(){let theme2=this.getThemeSetting();return theme2?.includes("/")?void 0:theme2}setTheme(theme2){this.globalSettings.theme=theme2,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(level){this.globalSettings.defaultThinkingLevel=level,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(provider,modelId){return this.settings.modelThinkingLevels?.[`${provider}/${modelId}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(provider,modelId,level){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`]=level,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(provider,modelId){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(transport){this.globalSettings.transport=transport,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(enabled){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=enabled,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getMicrocompactEnabled(){return this.settings.compaction?.microcompactEnabled??!0}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens(),microcompactEnabled:this.getMicrocompactEnabled()}}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?`
|
|
1060
1060
|
Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
|
|
1061
1061
|
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
|
|
1062
1062
|
${issue.sessionCwd}
|