herm-tui 1.9.0-dev.27 → 1.9.0-dev.29
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/README.md +9 -5
- package/assets/skills/eikon/SKILL.md +9 -4
- package/assets/skills/eikon-create/SKILL.md +3 -1
- package/index.js +53 -51
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -3273,7 +3273,7 @@ ${inner}
|
|
|
3273
3273
|
${closingIndent}}`}default:return"any"}}function formatFunctionDefinitions(functions){let lines3=["namespace functions {",""];for(let fn of functions){if(fn.description)lines3.push(`// ${fn.description}`);let{parameters}=fn,properties=parameters?.properties;if(!parameters||!properties||Object.keys(properties).length===0)lines3.push(`type ${fn.name} = () => any;`);else{lines3.push(`type ${fn.name} = (_: {`);let formattedProperties=formatObjectProperties(parameters,0,formatFunctionType);if(formattedProperties.length>0)lines3.push(formattedProperties);lines3.push("}) => any;")}lines3.push("")}return lines3.push("} // namespace functions"),lines3.join(`
|
|
3274
3274
|
`)}function estimateTokensInFunctions(functions,countStringTokens){let formatted=formatFunctionDefinitions(functions),tokens2=countStringTokens(formatted);return tokens2+=exports.FUNCTION_DEFINITION_TOKEN_OVERHEAD,tokens2}function padSystemMessage(message,hasFunctions,isSystemPadded){if(!hasFunctions||isSystemPadded||message.role!=="system")return message;if(!message.content||message.content.endsWith(NEWLINE))return message;return{...message,content:`${message.content}${NEWLINE}`}}function computeChatCompletionTokenCount(request,countStringTokens){let{messages,functions,function_call:functionCall}=request,hasFunctions=Boolean(functions&&functions.length>0),paddedSystem=!1,total=0;for(let message of messages){let messageToCount=padSystemMessage(message,hasFunctions,paddedSystem);if(messageToCount!==message&&message.role==="system")paddedSystem=!0;else if(message.role==="system"&&hasFunctions&&!paddedSystem)paddedSystem=!0;total+=countMessageTokens(messageToCount,countStringTokens)}if(total+=exports.COMPLETION_REQUEST_TOKEN_OVERHEAD,hasFunctions&&functions){if(total+=estimateTokensInFunctions(functions,countStringTokens),messages.some((message)=>message.role==="system"))total-=exports.SYSTEM_FUNCTION_TOKEN_DEDUCTION}if(functionCall&&functionCall!=="auto"){if(functionCall==="none")total+=exports.FUNCTION_CALL_NONE_TOKEN_OVERHEAD;else if(typeof functionCall==="object"&&functionCall.name)total+=countStringTokens(functionCall.name)+exports.FUNCTION_CALL_NAME_TOKEN_OVERHEAD}return total}});var require_modelsChatEnabled_gen=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.chatEnabledModels=void 0;exports.chatEnabledModels=["chatgpt-4o-latest","codex-mini-latest","computer-use-preview","computer-use-preview-2025-03-11","gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-audio-preview-2025-06-03","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4o-mini-audio-preview","gpt-4o-mini-audio-preview-2024-12-17","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-5","gpt-5-2025-08-07","gpt-5-chat-latest","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-audio","gpt-audio-2025-08-28","gpt-audio-mini","gpt-audio-mini-2025-10-06","gpt-oss-120b","gpt-oss-20b","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","o1-preview","o1-preview-2024-09-12","o1-pro","o1-pro-2025-03-19","o3","o3-2025-04-16","o3-deep-research","o3-deep-research-2025-06-26","o3-mini","o3-mini-2025-01-31","o3-pro","o3-pro-2025-06-10","o4-mini","o4-mini-2025-04-16","o4-mini-deep-research","o4-mini-deep-research-2025-06-26"]});var require_modelsMap=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.o200k_harmony=exports.o200k_base=exports.cl100k_base=exports.p50k_edit=exports.r50k_base=exports.p50k_base=void 0;exports.p50k_base=["text-davinci-002","text-davinci-003","code-davinci-001","code-davinci-002","davinci-codex","code-cushman-001","code-cushman-002","cushman-codex"];exports.r50k_base=["text-ada-001","text-babbage-001","text-curie-001","text-davinci-001","ada","babbage","curie","davinci","code-search-ada-code-001","code-search-ada-text-001","text-similarity-ada-001","text-search-ada-doc-001","text-search-ada-query-001","text-similarity-babbage-001","text-search-babbage-doc-001","text-search-babbage-query-001","code-search-babbage-code-001","code-search-babbage-text-001","text-similarity-curie-001","text-search-curie-doc-001","text-search-curie-query-001","text-similarity-davinci-001","text-search-davinci-doc-001","text-search-davinci-query-001"];exports.p50k_edit=["code-davinci-edit-001","text-davinci-edit-001"];exports.cl100k_base=["gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","text-embedding-3-large","text-embedding-3-small","text-embedding-ada-002","babbage-002","davinci-002"];exports.o200k_base=[];exports.o200k_harmony=["gpt-oss-20b","gpt-oss-120b"]});var require_specialTokens=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.HarmonyCall=exports.HarmonyConstrain=exports.HarmonyReturn=exports.HarmonyChannel=exports.HarmonyMessage=exports.HarmonyEnd=exports.HarmonyStart=exports.HarmonyStartOfText=exports.EndOfPrompt=exports.ImSep=exports.ImEnd=exports.ImStart=exports.FimSuffix=exports.FimMiddle=exports.FimPrefix=exports.EndOfText=void 0;exports.EndOfText="<|endoftext|>";exports.FimPrefix="<|fim_prefix|>";exports.FimMiddle="<|fim_middle|>";exports.FimSuffix="<|fim_suffix|>";exports.ImStart="<|im_start|>";exports.ImEnd="<|im_end|>";exports.ImSep="<|im_sep|>";exports.EndOfPrompt="<|endofprompt|>";exports.HarmonyStartOfText="<|startoftext|>";exports.HarmonyStart="<|start|>";exports.HarmonyEnd="<|end|>";exports.HarmonyMessage="<|message|>";exports.HarmonyChannel="<|channel|>";exports.HarmonyReturn="<|return|>";exports.HarmonyConstrain="<|constrain|>";exports.HarmonyCall="<|call|>"});var require_mapping=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m2,k2,k22){if(k22===void 0)k22=k2;var desc=Object.getOwnPropertyDescriptor(m2,k2);if(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m2[k2]}};Object.defineProperty(o,k22,desc)}:function(o,m2,k2,k22){if(k22===void 0)k22=k2;o[k22]=m2[k2]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v2){Object.defineProperty(o,"default",{enumerable:!0,value:v2})}:function(o,v2){o.default=v2}),__importStar=exports&&exports.__importStar||function(){var ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k2 in o2)if(Object.prototype.hasOwnProperty.call(o2,k2))ar[ar.length]=k2;return ar},ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null){for(var k2=ownKeys(mod),i=0;i<k2.length;i++)if(k2[i]!=="default")__createBinding(result,mod,k2[i])}return __setModuleDefault(result,mod),result}}();Object.defineProperty(exports,"__esModule",{value:!0});exports.chatModelParams=exports.modelToEncodingMap=exports.encodingNames=exports.DEFAULT_ENCODING=exports.o200k_harmony=exports.o200k_base=exports.r50k_base=exports.p50k_edit=exports.p50k_base=exports.cl100k_base=void 0;var modelsChatEnabled_gen_js_1=require_modelsChatEnabled_gen(),encodingsMap=__importStar(require_modelsMap()),specialTokens_js_1=require_specialTokens();exports.cl100k_base="cl100k_base";exports.p50k_base="p50k_base";exports.p50k_edit="p50k_edit";exports.r50k_base="r50k_base";exports.o200k_base="o200k_base";exports.o200k_harmony="o200k_harmony";exports.DEFAULT_ENCODING=exports.o200k_base;exports.encodingNames=[exports.p50k_base,exports.r50k_base,exports.p50k_edit,exports.cl100k_base,exports.o200k_base,exports.o200k_harmony];exports.modelToEncodingMap=Object.fromEntries(Object.entries(encodingsMap).flatMap(([encodingName,models])=>models.map((modelName)=>[modelName,encodingName])));var gpt3params={messageSeparator:`
|
|
3275
3275
|
`,roleSeparator:`
|
|
3276
|
-
`},gpt4params={messageSeparator:"",roleSeparator:specialTokens_js_1.ImSep};exports.chatModelParams=Object.fromEntries(modelsChatEnabled_gen_js_1.chatEnabledModels.flatMap((modelName)=>modelName.startsWith("gpt-3.5")?[[modelName,gpt3params]]:[[modelName,gpt4params]]))});var require_constants2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.O200K_TOKEN_SPLIT_REGEX=exports.CL100K_TOKEN_SPLIT_REGEX=exports.R50K_TOKEN_SPLIT_REGEX=void 0;exports.R50K_TOKEN_SPLIT_REGEX=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;var CONTRACTION_SUFFIX_PATTERN=String.raw`'(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`,OPTIONAL_CONTRACTION_SUFFIX=String.raw`(?:${CONTRACTION_SUFFIX_PATTERN})?`,CL100K_TOKEN_SPLIT_PATTERN=String.raw`${CONTRACTION_SUFFIX_PATTERN}|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s+$|\s*[\r\n]|\s+(?!\S)|\s`;exports.CL100K_TOKEN_SPLIT_REGEX=new RegExp(CL100K_TOKEN_SPLIT_PATTERN,"gu");var O200K_TOKEN_SPLIT_PATTERN=String.raw`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+${OPTIONAL_CONTRACTION_SUFFIX}|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*${OPTIONAL_CONTRACTION_SUFFIX}|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`;exports.O200K_TOKEN_SPLIT_REGEX=new RegExp(O200K_TOKEN_SPLIT_PATTERN,"gu")});var require_cl100k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.Cl100KBase=Cl100KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function Cl100KBase(bytePairRankDecoder){let specialTokenMapping=new Map([[specialTokens_js_1.EndOfText,100257],[specialTokens_js_1.FimPrefix,100258],[specialTokens_js_1.FimMiddle,100259],[specialTokens_js_1.FimSuffix,100260],[specialTokens_js_1.ImStart,100264],[specialTokens_js_1.ImEnd,100265],[specialTokens_js_1.ImSep,100266],[specialTokens_js_1.EndOfPrompt,100276]]);return{tokenSplitRegex:constants_js_1.CL100K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}});var require_o200k_base2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.createO200KSpecialTokenMap=void 0;exports.O200KBase=O200KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2(),O200K_BASE_SPECIAL_TOKEN_ENTRIES=[[specialTokens_js_1.EndOfText,199999],[specialTokens_js_1.FimPrefix,200000],[specialTokens_js_1.FimMiddle,200001],[specialTokens_js_1.FimSuffix,200002],[specialTokens_js_1.ImStart,200003],[specialTokens_js_1.ImEnd,200004],[specialTokens_js_1.ImSep,200005],[specialTokens_js_1.EndOfPrompt,200006]],createO200KSpecialTokenMap=()=>new Map(O200K_BASE_SPECIAL_TOKEN_ENTRIES);exports.createO200KSpecialTokenMap=createO200KSpecialTokenMap;function O200KBase(bytePairRankDecoder){return{tokenSplitRegex:constants_js_1.O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:exports.createO200KSpecialTokenMap()}}});var require_o200k_harmony=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.O200KHarmony=O200KHarmony;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2(),RESERVED_TOKEN_RANGE_START=200013,RESERVED_TOKEN_RANGE_END=201088,STATIC_SPECIAL_TOKEN_ENTRIES=[[specialTokens_js_1.HarmonyStartOfText,199998],[specialTokens_js_1.EndOfText,199999],["<|reserved_200000|>",200000],["<|reserved_200001|>",200001],[specialTokens_js_1.HarmonyReturn,200002],[specialTokens_js_1.HarmonyConstrain,200003],["<|reserved_200004|>",200004],[specialTokens_js_1.HarmonyChannel,200005],[specialTokens_js_1.HarmonyStart,200006],[specialTokens_js_1.HarmonyEnd,200007],[specialTokens_js_1.HarmonyMessage,200008],["<|reserved_200009|>",200009],["<|reserved_200010|>",200010],["<|reserved_200011|>",200011],[specialTokens_js_1.HarmonyCall,200012]];function O200KHarmony(bytePairRankDecoder){let specialTokensEncoder=new Map(STATIC_SPECIAL_TOKEN_ENTRIES);for(let tokenId=RESERVED_TOKEN_RANGE_START;tokenId<RESERVED_TOKEN_RANGE_END;tokenId+=1)specialTokensEncoder.set(`<|reserved_${tokenId}|>`,tokenId);return specialTokensEncoder.set(specialTokens_js_1.EndOfPrompt,200018),{tokenSplitRegex:constants_js_1.O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder,chatFormatter:"harmony"}}});var require_p50k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.P50KBase=P50KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function P50KBase(bytePairRankDecoder){return{expectedVocabularySize:50281,tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[specialTokens_js_1.EndOfText,50256]])}}});var require_p50k_edit=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.P50KEdit=P50KEdit;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function P50KEdit(bytePairRankDecoder){let specialTokenMapping=new Map([[specialTokens_js_1.EndOfText,50256],[specialTokens_js_1.FimPrefix,50281],[specialTokens_js_1.FimMiddle,50282],[specialTokens_js_1.FimSuffix,50283]]);return{tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}});var require_r50k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.R50KBase=R50KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function R50KBase(bytePairRankDecoder){return{expectedVocabularySize:50257,tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[specialTokens_js_1.EndOfText,50256]])}}});var require_modelParams=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.getEncodingParams=getEncodingParams;var cl100k_base_js_1=require_cl100k_base(),o200k_base_js_1=require_o200k_base2(),o200k_harmony_js_1=require_o200k_harmony(),p50k_base_js_1=require_p50k_base(),p50k_edit_js_1=require_p50k_edit(),r50k_base_js_1=require_r50k_base();function getEncodingParams(encodingName,getMergeableRanks){let mergeableBytePairRanks=getMergeableRanks(encodingName);switch(encodingName.toLowerCase()){case"r50k_base":return(0,r50k_base_js_1.R50KBase)(mergeableBytePairRanks);case"p50k_base":return(0,p50k_base_js_1.P50KBase)(mergeableBytePairRanks);case"p50k_edit":return(0,p50k_edit_js_1.P50KEdit)(mergeableBytePairRanks);case"cl100k_base":return(0,cl100k_base_js_1.Cl100KBase)(mergeableBytePairRanks);case"o200k_base":return(0,o200k_base_js_1.O200KBase)(mergeableBytePairRanks);case"o200k_harmony":return(0,o200k_harmony_js_1.O200KHarmony)(mergeableBytePairRanks);default:throw Error(`Unknown encoding name: ${encodingName}`)}}});var require_GptEncoding=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.GptEncoding=void 0;var BytePairEncodingCore_js_1=require_BytePairEncodingCore(),constants_js_1=require_constants(),functionCalling_js_1=require_functionCalling(),mapping_js_1=require_mapping(),modelParams_js_1=require_modelParams(),specialTokens_js_1=require_specialTokens(),utfUtil_js_1=require_utfUtil(),util_js_1=require_util();class GptEncoding{static EndOfPrompt=specialTokens_js_1.EndOfPrompt;static EndOfText=specialTokens_js_1.EndOfText;static FimMiddle=specialTokens_js_1.FimMiddle;static FimPrefix=specialTokens_js_1.FimPrefix;static FimSuffix=specialTokens_js_1.FimSuffix;modelName;modelSpec;bytePairEncodingCoreProcessor;specialTokensEncoder;specialTokensSet;allSpecialTokenRegex;defaultSpecialTokenConfig;chatFormatter;countChatCompletionTokens;vocabularySize;constructor({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,expectedVocabularySize,modelName,modelSpec,chatFormatter,...rest}){this.specialTokensEncoder=specialTokensEncoder,this.specialTokensSet=new Set(this.specialTokensEncoder.keys()),this.allSpecialTokenRegex=(0,util_js_1.getSpecialTokenRegex)(this.specialTokensSet),this.bytePairEncodingCoreProcessor=new BytePairEncodingCore_js_1.BytePairEncodingCore({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,...rest}),this.defaultSpecialTokenConfig=this.processSpecialTokens();let maxTokenValue=Math.max(mergeableBytePairRanks.length-1,(0,util_js_1.getMaxValueFromMap)(specialTokensEncoder));if(this.vocabularySize=this.bytePairEncodingCoreProcessor.mergeableBytePairRankCount+specialTokensEncoder.size,expectedVocabularySize!==void 0){if(this.vocabularySize!==expectedVocabularySize)throw Error("The number of mergeable tokens and special tokens must be equal to expectedVocabularySize.");if(maxTokenValue!==expectedVocabularySize-1)throw Error(`The model encodings are invalid. The maximum token value must be equal to expectedVocabularySize - 1. Currently ${maxTokenValue}, expected ${expectedVocabularySize-1}`)}if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),this.encodeGenerator=this.encodeGenerator.bind(this),this.decodeGenerator=this.decodeGenerator.bind(this),this.decodeAsyncGenerator=this.decodeAsyncGenerator.bind(this),this.decodeAsync=this.decodeAsync.bind(this),this.isWithinTokenLimit=this.isWithinTokenLimit.bind(this),this.encodeChat=this.encodeChat.bind(this),this.encodeChatGenerator=this.encodeChatGenerator.bind(this),this.countTokens=this.countTokens.bind(this),this.setMergeCacheSize=this.setMergeCacheSize.bind(this),this.clearMergeCache=this.clearMergeCache.bind(this),this.estimateCost=this.estimateCost.bind(this),modelSpec?.supported_features?.includes("function_calling"))this.countChatCompletionTokens=this.countChatCompletionTokensInternal.bind(this);this.modelName=modelName,this.modelSpec=modelSpec,this.chatFormatter=chatFormatter??"chatml"}*encodeHarmonyChatGenerator(chat,encodeOptions){let harmonyStart=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyStart),harmonyMessage=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyMessage),harmonyEnd=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyEnd),harmonyReturn=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyReturn),harmonyCall=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyCall),harmonyChannel=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyChannel),harmonyConstrain=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyConstrain);if(harmonyStart===void 0||harmonyMessage===void 0||harmonyEnd===void 0||harmonyReturn===void 0||harmonyCall===void 0||harmonyChannel===void 0||harmonyConstrain===void 0)throw Error("Harmony chat format requires dedicated special tokens.");let encodeHeaderText=(text3)=>text3.length>0?this.encode(text3):[],resolveTerminatorToken=(terminator)=>{switch(terminator){case"<|return|>":return harmonyReturn;case"<|call|>":return harmonyCall;case"<|end|>":default:return harmonyEnd}};for(let message of chat){if(message.content===void 0)throw Error("Content must be defined for all messages.");let roleOrName=message.name??message.role??"user";yield[harmonyStart],yield encodeHeaderText(roleOrName);let recipientInRole=message.recipient&&(message.recipientPlacement==="role"||!message.channel),recipientInChannel=message.recipient&&!recipientInRole;if(recipientInRole)yield encodeHeaderText(` to=${message.recipient}`);if(message.channel){if(yield[harmonyChannel],yield encodeHeaderText(message.channel),recipientInChannel)yield encodeHeaderText(` to=${message.recipient}`)}if(message.constraint)yield[harmonyConstrain],yield encodeHeaderText(message.constraint);yield[harmonyMessage],yield*this.encodeGenerator(message.content,encodeOptions),yield[resolveTerminatorToken(message.terminator)]}let assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0)yield[harmonyStart],yield encodeHeaderText(assistantPrime)}static getEncodingApi(encodingName,getMergeableRanks){let modelParams=(0,modelParams_js_1.getEncodingParams)(encodingName,getMergeableRanks);return new GptEncoding(modelParams)}static getEncodingApiForModel(modelName,getMergeableRanks,modelSpec){let encodingName=mapping_js_1.modelToEncodingMap[modelName]??mapping_js_1.DEFAULT_ENCODING,modelParams=(0,modelParams_js_1.getEncodingParams)(encodingName,getMergeableRanks);return new GptEncoding({...modelParams,modelName,modelSpec})}processSpecialTokens({allowedSpecial,disallowedSpecial}={}){let regexPattern;if(allowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS||allowedSpecial?.has(constants_js_1.ALL_SPECIAL_TOKENS)){allowedSpecial=new Set(this.specialTokensSet);let allowedSpecialSet=allowedSpecial;if(disallowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS)throw Error('allowedSpecial and disallowedSpecial cannot both be set to "all".');if(typeof disallowedSpecial==="object")disallowedSpecial.forEach((val)=>allowedSpecialSet.delete(val));else disallowedSpecial=new Set}if(!disallowedSpecial||disallowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS||disallowedSpecial.has(constants_js_1.ALL_SPECIAL_TOKENS)){disallowedSpecial=new Set(this.specialTokensSet);let disallowedSpecialSet=disallowedSpecial;if(allowedSpecial?.size){if(allowedSpecial.forEach((val)=>disallowedSpecialSet.delete(val)),disallowedSpecial.forEach((val)=>allowedSpecial.delete(val)),disallowedSpecial.size>0)regexPattern=(0,util_js_1.getSpecialTokenRegex)(disallowedSpecial)}else regexPattern=this.allSpecialTokenRegex}return{allowedSpecial,regexPattern}}encodeGenerator(lineToEncode,encodeOptions){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=lineToEncode.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNativeGenerator(lineToEncode,specialTokenConfig.allowedSpecial)}encode(lineToEncode,encodeOptions){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=lineToEncode.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNative(lineToEncode,specialTokenConfig.allowedSpecial)}*encodeChatGenerator(chat,model=this.modelName,encodeOptions){if(!model)throw Error("Model name must be provided either during initialization or passed in to the method.");let params=mapping_js_1.chatModelParams[model];if(!params)throw Error(`Model '${model}' does not support chat.`);if(this.chatFormatter==="harmony"){yield*this.encodeHarmonyChatGenerator(chat,encodeOptions);return}let chatStartToken=this.specialTokensEncoder.get(specialTokens_js_1.ImStart),chatEndToken=this.specialTokensEncoder.get(specialTokens_js_1.ImEnd);if(chatStartToken===void 0||chatEndToken===void 0)throw Error(`Model '${model}' does not support chat.`);let allowedSpecial=new Set([specialTokens_js_1.ImSep]),{messageSeparator,roleSeparator}=params,encodedMessageSeparator=messageSeparator.length>0?this.encode(messageSeparator):[],encodedRoleSeparator=roleSeparator.length>0?this.encode(roleSeparator,{allowedSpecial}):[],nameCache=new Map;for(let{role="system",name=role,content}of chat){if(content===void 0)throw Error("Content must be defined for all messages.");yield[chatStartToken];let encodedName=nameCache.get(name)??this.encode(name);if(nameCache.set(name,encodedName),yield encodedName,encodedRoleSeparator.length>0)yield encodedRoleSeparator;yield*this.encodeGenerator(content,encodeOptions),yield[chatEndToken],yield encodedMessageSeparator}let assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0)yield[chatStartToken],yield*this.encodeGenerator(assistantPrime,encodeOptions);if(encodedRoleSeparator.length>0)yield encodedRoleSeparator}encodeChat(chat,model=this.modelName,encodeOptions){return[...this.encodeChatGenerator(chat,model,encodeOptions)].flat()}isWithinTokenLimit(input,tokenLimit,encodeOptions){let tokenGenerator=typeof input==="string"?this.encodeGenerator(input,encodeOptions):this.encodeChatGenerator(input,void 0,encodeOptions),count2=0;for(let tokens2 of tokenGenerator)if(count2+=tokens2.length,count2>tokenLimit)return!1;return count2}countTokens(input,encodeOptions){if(typeof input==="string"){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=input.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.countNative(input,specialTokenConfig.allowedSpecial)}let tokenGenerator=this.encodeChatGenerator(input,void 0,encodeOptions),count2=0;for(let tokens2 of tokenGenerator)count2+=tokens2.length;return count2}countStringTokens(text3){if(!text3)return 0;return this.bytePairEncodingCoreProcessor.countNative(text3)}countChatCompletionTokensInternal(request){return(0,functionCalling_js_1.computeChatCompletionTokenCount)(request,(text3)=>this.countStringTokens(text3))}setMergeCacheSize(size){this.bytePairEncodingCoreProcessor.setMergeCacheSize(size)}clearMergeCache(){this.bytePairEncodingCoreProcessor.clearMergeCache()}decode(inputTokensToDecode){return this.bytePairEncodingCoreProcessor.decodeNative(inputTokensToDecode)}*decodeGenerator(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeGenerator(inputTokensToDecode),buffer2="";for(let decodedPart of decodedByteGenerator)if(buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0}),buffer2.length===0||(0,utfUtil_js_1.endsWithIncompleteUtfPairSurrogate)(buffer2))continue;else yield buffer2,buffer2="";if(buffer2.length>0)yield buffer2}async*decodeAsyncGenerator(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode),buffer2="";for await(let decodedPart of decodedByteGenerator)if(buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0}),buffer2.length===0||(0,utfUtil_js_1.endsWithIncompleteUtfPairSurrogate)(buffer2))continue;else yield buffer2,buffer2="";if(buffer2.length>0)yield buffer2}async decodeAsync(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode),buffer2="";for await(let decodedPart of decodedByteGenerator)buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0});return buffer2}estimateCost(tokenCount,modelSpec=this.modelSpec){if(!modelSpec)throw Error("Model spec must be provided either during initialization or passed in to the method.");if(!modelSpec.price_data)throw Error(`No cost information available for model: ${modelSpec.name}`);let priceDataPerMillion=modelSpec.price_data,result={},millionTokens=tokenCount/1e6;if(priceDataPerMillion.main)result.main={input:priceDataPerMillion.main.input&&priceDataPerMillion.main.input*millionTokens,output:priceDataPerMillion.main.output&&priceDataPerMillion.main.output*millionTokens,cached_input:priceDataPerMillion.main.cached_input&&priceDataPerMillion.main.cached_input*millionTokens,cached_output:priceDataPerMillion.main.cached_output&&priceDataPerMillion.main.cached_output*millionTokens};if(priceDataPerMillion.batch)result.batch={input:priceDataPerMillion.batch.input&&priceDataPerMillion.batch.input*millionTokens,output:priceDataPerMillion.batch.output&&priceDataPerMillion.batch.output*millionTokens,cached_input:priceDataPerMillion.batch.cached_input&&priceDataPerMillion.batch.cached_input*millionTokens,cached_output:priceDataPerMillion.batch.cached_output&&priceDataPerMillion.batch.cached_output*millionTokens};return result}}exports.GptEncoding=GptEncoding});var require_o200k_base3=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m2,k2,k22){if(k22===void 0)k22=k2;var desc=Object.getOwnPropertyDescriptor(m2,k2);if(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m2[k2]}};Object.defineProperty(o,k22,desc)}:function(o,m2,k2,k22){if(k22===void 0)k22=k2;o[k22]=m2[k2]}),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m2,p)},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.vocabularySize=exports.setMergeCacheSize=exports.isWithinTokenLimit=exports.estimateCost=exports.encodeGenerator=exports.encodeChatGenerator=exports.encodeChat=exports.encode=exports.decodeGenerator=exports.decodeAsyncGenerator=exports.decode=exports.countTokens=exports.clearMergeCache=void 0;var o200k_base_js_1=__importDefault(require_o200k_base()),GptEncoding_js_1=require_GptEncoding();__exportStar(require_constants(),exports);__exportStar(require_specialTokens(),exports);var api=GptEncoding_js_1.GptEncoding.getEncodingApi("o200k_base",()=>o200k_base_js_1.default),{decode:decode2,decodeAsyncGenerator,decodeGenerator,encode,encodeGenerator,isWithinTokenLimit,countTokens,encodeChat,encodeChatGenerator,vocabularySize,setMergeCacheSize,clearMergeCache,estimateCost}=api;exports.decode=decode2;exports.decodeAsyncGenerator=decodeAsyncGenerator;exports.decodeGenerator=decodeGenerator;exports.encode=encode;exports.encodeGenerator=encodeGenerator;exports.isWithinTokenLimit=isWithinTokenLimit;exports.countTokens=countTokens;exports.encodeChat=encodeChat;exports.encodeChatGenerator=encodeChatGenerator;exports.vocabularySize=vocabularySize;exports.setMergeCacheSize=setMergeCacheSize;exports.clearMergeCache=clearMergeCache;exports.estimateCost=estimateCost;exports.default=api});var require_main=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m2,k2,k22){if(k22===void 0)k22=k2;var desc=Object.getOwnPropertyDescriptor(m2,k2);if(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m2[k2]}};Object.defineProperty(o,k22,desc)}:function(o,m2,k2,k22){if(k22===void 0)k22=k2;o[k22]=m2[k2]}),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m2,p)},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.default=void 0;var o200k_base_js_1=require_o200k_base3();Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return __importDefault(o200k_base_js_1).default}});__exportStar(require_o200k_base3(),exports)});var exports_sessions_db={};__export(exports_sessions_db,{systemPrompt:()=>systemPrompt,stateDb:()=>stateDb,setHome:()=>setHome,search:()=>search,sdb:()=>exports_sessions_db,roots:()=>roots,resetDb:()=>resetDb,rename:()=>rename,remove:()=>remove,peek:()=>peek4,lineage:()=>lineage,lastReal:()=>lastReal,kind:()=>kind,goalState:()=>goalState,children:()=>children,chainTip:()=>chainTip,byId:()=>byId});import{Database}from"bun:sqlite";import{homedir as homedir3}from"os";function walkUp(sid){let step=q2(`SELECT p.id FROM sessions c
|
|
3276
|
+
`},gpt4params={messageSeparator:"",roleSeparator:specialTokens_js_1.ImSep};exports.chatModelParams=Object.fromEntries(modelsChatEnabled_gen_js_1.chatEnabledModels.flatMap((modelName)=>modelName.startsWith("gpt-3.5")?[[modelName,gpt3params]]:[[modelName,gpt4params]]))});var require_constants2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.O200K_TOKEN_SPLIT_REGEX=exports.CL100K_TOKEN_SPLIT_REGEX=exports.R50K_TOKEN_SPLIT_REGEX=void 0;exports.R50K_TOKEN_SPLIT_REGEX=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;var CONTRACTION_SUFFIX_PATTERN=String.raw`'(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`,OPTIONAL_CONTRACTION_SUFFIX=String.raw`(?:${CONTRACTION_SUFFIX_PATTERN})?`,CL100K_TOKEN_SPLIT_PATTERN=String.raw`${CONTRACTION_SUFFIX_PATTERN}|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s+$|\s*[\r\n]|\s+(?!\S)|\s`;exports.CL100K_TOKEN_SPLIT_REGEX=new RegExp(CL100K_TOKEN_SPLIT_PATTERN,"gu");var O200K_TOKEN_SPLIT_PATTERN=String.raw`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+${OPTIONAL_CONTRACTION_SUFFIX}|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*${OPTIONAL_CONTRACTION_SUFFIX}|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`;exports.O200K_TOKEN_SPLIT_REGEX=new RegExp(O200K_TOKEN_SPLIT_PATTERN,"gu")});var require_cl100k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.Cl100KBase=Cl100KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function Cl100KBase(bytePairRankDecoder){let specialTokenMapping=new Map([[specialTokens_js_1.EndOfText,100257],[specialTokens_js_1.FimPrefix,100258],[specialTokens_js_1.FimMiddle,100259],[specialTokens_js_1.FimSuffix,100260],[specialTokens_js_1.ImStart,100264],[specialTokens_js_1.ImEnd,100265],[specialTokens_js_1.ImSep,100266],[specialTokens_js_1.EndOfPrompt,100276]]);return{tokenSplitRegex:constants_js_1.CL100K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}});var require_o200k_base2=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.createO200KSpecialTokenMap=void 0;exports.O200KBase=O200KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2(),O200K_BASE_SPECIAL_TOKEN_ENTRIES=[[specialTokens_js_1.EndOfText,199999],[specialTokens_js_1.FimPrefix,200000],[specialTokens_js_1.FimMiddle,200001],[specialTokens_js_1.FimSuffix,200002],[specialTokens_js_1.ImStart,200003],[specialTokens_js_1.ImEnd,200004],[specialTokens_js_1.ImSep,200005],[specialTokens_js_1.EndOfPrompt,200006]],createO200KSpecialTokenMap=()=>new Map(O200K_BASE_SPECIAL_TOKEN_ENTRIES);exports.createO200KSpecialTokenMap=createO200KSpecialTokenMap;function O200KBase(bytePairRankDecoder){return{tokenSplitRegex:constants_js_1.O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:exports.createO200KSpecialTokenMap()}}});var require_o200k_harmony=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.O200KHarmony=O200KHarmony;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2(),RESERVED_TOKEN_RANGE_START=200013,RESERVED_TOKEN_RANGE_END=201088,STATIC_SPECIAL_TOKEN_ENTRIES=[[specialTokens_js_1.HarmonyStartOfText,199998],[specialTokens_js_1.EndOfText,199999],["<|reserved_200000|>",200000],["<|reserved_200001|>",200001],[specialTokens_js_1.HarmonyReturn,200002],[specialTokens_js_1.HarmonyConstrain,200003],["<|reserved_200004|>",200004],[specialTokens_js_1.HarmonyChannel,200005],[specialTokens_js_1.HarmonyStart,200006],[specialTokens_js_1.HarmonyEnd,200007],[specialTokens_js_1.HarmonyMessage,200008],["<|reserved_200009|>",200009],["<|reserved_200010|>",200010],["<|reserved_200011|>",200011],[specialTokens_js_1.HarmonyCall,200012]];function O200KHarmony(bytePairRankDecoder){let specialTokensEncoder=new Map(STATIC_SPECIAL_TOKEN_ENTRIES);for(let tokenId=RESERVED_TOKEN_RANGE_START;tokenId<RESERVED_TOKEN_RANGE_END;tokenId+=1)specialTokensEncoder.set(`<|reserved_${tokenId}|>`,tokenId);return specialTokensEncoder.set(specialTokens_js_1.EndOfPrompt,200018),{tokenSplitRegex:constants_js_1.O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder,chatFormatter:"harmony"}}});var require_p50k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.P50KBase=P50KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function P50KBase(bytePairRankDecoder){return{expectedVocabularySize:50281,tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[specialTokens_js_1.EndOfText,50256]])}}});var require_p50k_edit=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.P50KEdit=P50KEdit;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function P50KEdit(bytePairRankDecoder){let specialTokenMapping=new Map([[specialTokens_js_1.EndOfText,50256],[specialTokens_js_1.FimPrefix,50281],[specialTokens_js_1.FimMiddle,50282],[specialTokens_js_1.FimSuffix,50283]]);return{tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}});var require_r50k_base=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.R50KBase=R50KBase;var specialTokens_js_1=require_specialTokens(),constants_js_1=require_constants2();function R50KBase(bytePairRankDecoder){return{expectedVocabularySize:50257,tokenSplitRegex:constants_js_1.R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[specialTokens_js_1.EndOfText,50256]])}}});var require_modelParams=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.getEncodingParams=getEncodingParams;var cl100k_base_js_1=require_cl100k_base(),o200k_base_js_1=require_o200k_base2(),o200k_harmony_js_1=require_o200k_harmony(),p50k_base_js_1=require_p50k_base(),p50k_edit_js_1=require_p50k_edit(),r50k_base_js_1=require_r50k_base();function getEncodingParams(encodingName,getMergeableRanks){let mergeableBytePairRanks=getMergeableRanks(encodingName);switch(encodingName.toLowerCase()){case"r50k_base":return(0,r50k_base_js_1.R50KBase)(mergeableBytePairRanks);case"p50k_base":return(0,p50k_base_js_1.P50KBase)(mergeableBytePairRanks);case"p50k_edit":return(0,p50k_edit_js_1.P50KEdit)(mergeableBytePairRanks);case"cl100k_base":return(0,cl100k_base_js_1.Cl100KBase)(mergeableBytePairRanks);case"o200k_base":return(0,o200k_base_js_1.O200KBase)(mergeableBytePairRanks);case"o200k_harmony":return(0,o200k_harmony_js_1.O200KHarmony)(mergeableBytePairRanks);default:throw Error(`Unknown encoding name: ${encodingName}`)}}});var require_GptEncoding=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.GptEncoding=void 0;var BytePairEncodingCore_js_1=require_BytePairEncodingCore(),constants_js_1=require_constants(),functionCalling_js_1=require_functionCalling(),mapping_js_1=require_mapping(),modelParams_js_1=require_modelParams(),specialTokens_js_1=require_specialTokens(),utfUtil_js_1=require_utfUtil(),util_js_1=require_util();class GptEncoding{static EndOfPrompt=specialTokens_js_1.EndOfPrompt;static EndOfText=specialTokens_js_1.EndOfText;static FimMiddle=specialTokens_js_1.FimMiddle;static FimPrefix=specialTokens_js_1.FimPrefix;static FimSuffix=specialTokens_js_1.FimSuffix;modelName;modelSpec;bytePairEncodingCoreProcessor;specialTokensEncoder;specialTokensSet;allSpecialTokenRegex;defaultSpecialTokenConfig;chatFormatter;countChatCompletionTokens;vocabularySize;constructor({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,expectedVocabularySize,modelName,modelSpec,chatFormatter,...rest}){this.specialTokensEncoder=specialTokensEncoder,this.specialTokensSet=new Set(this.specialTokensEncoder.keys()),this.allSpecialTokenRegex=(0,util_js_1.getSpecialTokenRegex)(this.specialTokensSet),this.bytePairEncodingCoreProcessor=new BytePairEncodingCore_js_1.BytePairEncodingCore({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,...rest}),this.defaultSpecialTokenConfig=this.processSpecialTokens();let maxTokenValue=Math.max(mergeableBytePairRanks.length-1,(0,util_js_1.getMaxValueFromMap)(specialTokensEncoder));if(this.vocabularySize=this.bytePairEncodingCoreProcessor.mergeableBytePairRankCount+specialTokensEncoder.size,expectedVocabularySize!==void 0){if(this.vocabularySize!==expectedVocabularySize)throw Error("The number of mergeable tokens and special tokens must be equal to expectedVocabularySize.");if(maxTokenValue!==expectedVocabularySize-1)throw Error(`The model encodings are invalid. The maximum token value must be equal to expectedVocabularySize - 1. Currently ${maxTokenValue}, expected ${expectedVocabularySize-1}`)}if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),this.encodeGenerator=this.encodeGenerator.bind(this),this.decodeGenerator=this.decodeGenerator.bind(this),this.decodeAsyncGenerator=this.decodeAsyncGenerator.bind(this),this.decodeAsync=this.decodeAsync.bind(this),this.isWithinTokenLimit=this.isWithinTokenLimit.bind(this),this.encodeChat=this.encodeChat.bind(this),this.encodeChatGenerator=this.encodeChatGenerator.bind(this),this.countTokens=this.countTokens.bind(this),this.setMergeCacheSize=this.setMergeCacheSize.bind(this),this.clearMergeCache=this.clearMergeCache.bind(this),this.estimateCost=this.estimateCost.bind(this),modelSpec?.supported_features?.includes("function_calling"))this.countChatCompletionTokens=this.countChatCompletionTokensInternal.bind(this);this.modelName=modelName,this.modelSpec=modelSpec,this.chatFormatter=chatFormatter??"chatml"}*encodeHarmonyChatGenerator(chat,encodeOptions){let harmonyStart=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyStart),harmonyMessage=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyMessage),harmonyEnd=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyEnd),harmonyReturn=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyReturn),harmonyCall=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyCall),harmonyChannel=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyChannel),harmonyConstrain=this.specialTokensEncoder.get(specialTokens_js_1.HarmonyConstrain);if(harmonyStart===void 0||harmonyMessage===void 0||harmonyEnd===void 0||harmonyReturn===void 0||harmonyCall===void 0||harmonyChannel===void 0||harmonyConstrain===void 0)throw Error("Harmony chat format requires dedicated special tokens.");let encodeHeaderText=(text3)=>text3.length>0?this.encode(text3):[],resolveTerminatorToken=(terminator)=>{switch(terminator){case"<|return|>":return harmonyReturn;case"<|call|>":return harmonyCall;case"<|end|>":default:return harmonyEnd}};for(let message of chat){if(message.content===void 0)throw Error("Content must be defined for all messages.");let roleOrName=message.name??message.role??"user";yield[harmonyStart],yield encodeHeaderText(roleOrName);let recipientInRole=message.recipient&&(message.recipientPlacement==="role"||!message.channel),recipientInChannel=message.recipient&&!recipientInRole;if(recipientInRole)yield encodeHeaderText(` to=${message.recipient}`);if(message.channel){if(yield[harmonyChannel],yield encodeHeaderText(message.channel),recipientInChannel)yield encodeHeaderText(` to=${message.recipient}`)}if(message.constraint)yield[harmonyConstrain],yield encodeHeaderText(message.constraint);yield[harmonyMessage],yield*this.encodeGenerator(message.content,encodeOptions),yield[resolveTerminatorToken(message.terminator)]}let assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0)yield[harmonyStart],yield encodeHeaderText(assistantPrime)}static getEncodingApi(encodingName,getMergeableRanks){let modelParams=(0,modelParams_js_1.getEncodingParams)(encodingName,getMergeableRanks);return new GptEncoding(modelParams)}static getEncodingApiForModel(modelName,getMergeableRanks,modelSpec){let encodingName=mapping_js_1.modelToEncodingMap[modelName]??mapping_js_1.DEFAULT_ENCODING,modelParams=(0,modelParams_js_1.getEncodingParams)(encodingName,getMergeableRanks);return new GptEncoding({...modelParams,modelName,modelSpec})}processSpecialTokens({allowedSpecial,disallowedSpecial}={}){let regexPattern;if(allowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS||allowedSpecial?.has(constants_js_1.ALL_SPECIAL_TOKENS)){allowedSpecial=new Set(this.specialTokensSet);let allowedSpecialSet=allowedSpecial;if(disallowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS)throw Error('allowedSpecial and disallowedSpecial cannot both be set to "all".');if(typeof disallowedSpecial==="object")disallowedSpecial.forEach((val)=>allowedSpecialSet.delete(val));else disallowedSpecial=new Set}if(!disallowedSpecial||disallowedSpecial===constants_js_1.ALL_SPECIAL_TOKENS||disallowedSpecial.has(constants_js_1.ALL_SPECIAL_TOKENS)){disallowedSpecial=new Set(this.specialTokensSet);let disallowedSpecialSet=disallowedSpecial;if(allowedSpecial?.size){if(allowedSpecial.forEach((val)=>disallowedSpecialSet.delete(val)),disallowedSpecial.forEach((val)=>allowedSpecial.delete(val)),disallowedSpecial.size>0)regexPattern=(0,util_js_1.getSpecialTokenRegex)(disallowedSpecial)}else regexPattern=this.allSpecialTokenRegex}return{allowedSpecial,regexPattern}}encodeGenerator(lineToEncode,encodeOptions){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=lineToEncode.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNativeGenerator(lineToEncode,specialTokenConfig.allowedSpecial)}encode(lineToEncode,encodeOptions){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=lineToEncode.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.encodeNative(lineToEncode,specialTokenConfig.allowedSpecial)}*encodeChatGenerator(chat,model=this.modelName,encodeOptions){if(!model)throw Error("Model name must be provided either during initialization or passed in to the method.");let params=mapping_js_1.chatModelParams[model];if(!params)throw Error(`Model '${model}' does not support chat.`);if(this.chatFormatter==="harmony"){yield*this.encodeHarmonyChatGenerator(chat,encodeOptions);return}let chatStartToken=this.specialTokensEncoder.get(specialTokens_js_1.ImStart),chatEndToken=this.specialTokensEncoder.get(specialTokens_js_1.ImEnd);if(chatStartToken===void 0||chatEndToken===void 0)throw Error(`Model '${model}' does not support chat.`);let allowedSpecial=new Set([specialTokens_js_1.ImSep]),{messageSeparator,roleSeparator}=params,encodedMessageSeparator=messageSeparator.length>0?this.encode(messageSeparator):[],encodedRoleSeparator=roleSeparator.length>0?this.encode(roleSeparator,{allowedSpecial}):[],nameCache=new Map;for(let{role="system",name=role,content}of chat){if(content===void 0)throw Error("Content must be defined for all messages.");yield[chatStartToken];let encodedName=nameCache.get(name)??this.encode(name);if(nameCache.set(name,encodedName),yield encodedName,encodedRoleSeparator.length>0)yield encodedRoleSeparator;yield*this.encodeGenerator(content,encodeOptions),yield[chatEndToken],yield encodedMessageSeparator}let assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0)yield[chatStartToken],yield*this.encodeGenerator(assistantPrime,encodeOptions);if(encodedRoleSeparator.length>0)yield encodedRoleSeparator}encodeChat(chat,model=this.modelName,encodeOptions){return[...this.encodeChatGenerator(chat,model,encodeOptions)].flat()}isWithinTokenLimit(input,tokenLimit,encodeOptions){let tokenGenerator=typeof input==="string"?this.encodeGenerator(input,encodeOptions):this.encodeChatGenerator(input,void 0,encodeOptions),count2=0;for(let tokens2 of tokenGenerator)if(count2+=tokens2.length,count2>tokenLimit)return!1;return count2}countTokens(input,encodeOptions){if(typeof input==="string"){let specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){let match2=input.match(specialTokenConfig.regexPattern);if(match2!==null)throw Error(`Disallowed special token found: ${match2[0]}`)}return this.bytePairEncodingCoreProcessor.countNative(input,specialTokenConfig.allowedSpecial)}let tokenGenerator=this.encodeChatGenerator(input,void 0,encodeOptions),count2=0;for(let tokens2 of tokenGenerator)count2+=tokens2.length;return count2}countStringTokens(text3){if(!text3)return 0;return this.bytePairEncodingCoreProcessor.countNative(text3)}countChatCompletionTokensInternal(request){return(0,functionCalling_js_1.computeChatCompletionTokenCount)(request,(text3)=>this.countStringTokens(text3))}setMergeCacheSize(size){this.bytePairEncodingCoreProcessor.setMergeCacheSize(size)}clearMergeCache(){this.bytePairEncodingCoreProcessor.clearMergeCache()}decode(inputTokensToDecode){return this.bytePairEncodingCoreProcessor.decodeNative(inputTokensToDecode)}*decodeGenerator(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeGenerator(inputTokensToDecode),buffer2="";for(let decodedPart of decodedByteGenerator)if(buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0}),buffer2.length===0||(0,utfUtil_js_1.endsWithIncompleteUtfPairSurrogate)(buffer2))continue;else yield buffer2,buffer2="";if(buffer2.length>0)yield buffer2}async*decodeAsyncGenerator(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode),buffer2="";for await(let decodedPart of decodedByteGenerator)if(buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0}),buffer2.length===0||(0,utfUtil_js_1.endsWithIncompleteUtfPairSurrogate)(buffer2))continue;else yield buffer2,buffer2="";if(buffer2.length>0)yield buffer2}async decodeAsync(inputTokensToDecode){let decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode),buffer2="";for await(let decodedPart of decodedByteGenerator)buffer2+=typeof decodedPart==="string"?decodedPart:BytePairEncodingCore_js_1.decoder.decode(decodedPart,{stream:!0});return buffer2}estimateCost(tokenCount,modelSpec=this.modelSpec){if(!modelSpec)throw Error("Model spec must be provided either during initialization or passed in to the method.");if(!modelSpec.price_data)throw Error(`No cost information available for model: ${modelSpec.name}`);let priceDataPerMillion=modelSpec.price_data,result={},millionTokens=tokenCount/1e6;if(priceDataPerMillion.main)result.main={input:priceDataPerMillion.main.input&&priceDataPerMillion.main.input*millionTokens,output:priceDataPerMillion.main.output&&priceDataPerMillion.main.output*millionTokens,cached_input:priceDataPerMillion.main.cached_input&&priceDataPerMillion.main.cached_input*millionTokens,cached_output:priceDataPerMillion.main.cached_output&&priceDataPerMillion.main.cached_output*millionTokens};if(priceDataPerMillion.batch)result.batch={input:priceDataPerMillion.batch.input&&priceDataPerMillion.batch.input*millionTokens,output:priceDataPerMillion.batch.output&&priceDataPerMillion.batch.output*millionTokens,cached_input:priceDataPerMillion.batch.cached_input&&priceDataPerMillion.batch.cached_input*millionTokens,cached_output:priceDataPerMillion.batch.cached_output&&priceDataPerMillion.batch.cached_output*millionTokens};return result}}exports.GptEncoding=GptEncoding});var require_o200k_base3=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m2,k2,k22){if(k22===void 0)k22=k2;var desc=Object.getOwnPropertyDescriptor(m2,k2);if(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m2[k2]}};Object.defineProperty(o,k22,desc)}:function(o,m2,k2,k22){if(k22===void 0)k22=k2;o[k22]=m2[k2]}),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m2,p)},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.vocabularySize=exports.setMergeCacheSize=exports.isWithinTokenLimit=exports.estimateCost=exports.encodeGenerator=exports.encodeChatGenerator=exports.encodeChat=exports.encode=exports.decodeGenerator=exports.decodeAsyncGenerator=exports.decode=exports.countTokens=exports.clearMergeCache=void 0;var o200k_base_js_1=__importDefault(require_o200k_base()),GptEncoding_js_1=require_GptEncoding();__exportStar(require_constants(),exports);__exportStar(require_specialTokens(),exports);var api=GptEncoding_js_1.GptEncoding.getEncodingApi("o200k_base",()=>o200k_base_js_1.default),{decode:decode2,decodeAsyncGenerator,decodeGenerator,encode:encode2,encodeGenerator,isWithinTokenLimit,countTokens,encodeChat,encodeChatGenerator,vocabularySize,setMergeCacheSize,clearMergeCache,estimateCost}=api;exports.decode=decode2;exports.decodeAsyncGenerator=decodeAsyncGenerator;exports.decodeGenerator=decodeGenerator;exports.encode=encode2;exports.encodeGenerator=encodeGenerator;exports.isWithinTokenLimit=isWithinTokenLimit;exports.countTokens=countTokens;exports.encodeChat=encodeChat;exports.encodeChatGenerator=encodeChatGenerator;exports.vocabularySize=vocabularySize;exports.setMergeCacheSize=setMergeCacheSize;exports.clearMergeCache=clearMergeCache;exports.estimateCost=estimateCost;exports.default=api});var require_main=__commonJS((exports)=>{var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m2,k2,k22){if(k22===void 0)k22=k2;var desc=Object.getOwnPropertyDescriptor(m2,k2);if(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))desc={enumerable:!0,get:function(){return m2[k2]}};Object.defineProperty(o,k22,desc)}:function(o,m2,k2,k22){if(k22===void 0)k22=k2;o[k22]=m2[k2]}),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m2,p)},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.default=void 0;var o200k_base_js_1=require_o200k_base3();Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return __importDefault(o200k_base_js_1).default}});__exportStar(require_o200k_base3(),exports)});var exports_sessions_db={};__export(exports_sessions_db,{systemPrompt:()=>systemPrompt,stateDb:()=>stateDb,setHome:()=>setHome,search:()=>search,sdb:()=>exports_sessions_db,roots:()=>roots,resetDb:()=>resetDb,rename:()=>rename,remove:()=>remove,peek:()=>peek4,lineage:()=>lineage,lastReal:()=>lastReal,kind:()=>kind,goalState:()=>goalState,children:()=>children,chainTip:()=>chainTip,byId:()=>byId});import{Database}from"bun:sqlite";import{homedir as homedir3}from"os";function walkUp(sid){let step=q2(`SELECT p.id FROM sessions c
|
|
3277
3277
|
JOIN sessions p ON p.id = c.parent_session_id
|
|
3278
3278
|
WHERE c.id = ? AND ${CONT("c")}`),cur=sid;for(let i=0;i<100;i++){let prev=step?.get(cur);if(!prev)return cur;cur=prev.id}return cur}function roots(limit=30){let end=mark("io:sessions.roots");try{return(q2(`SELECT ${COLS} FROM sessions s
|
|
3279
3279
|
WHERE s.parent_session_id IS NULL
|
|
@@ -3425,8 +3425,8 @@ ${pointer}
|
|
|
3425
3425
|
`+props.comment;else coll.comment=props.comment;offset=props.end;continue}if(!isMap&&ctx.options.strict&&utilContainsNewline.containsNewline(key3))onError(key3,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(i===0){if(props.comma)onError(props.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${fcName}`)}else{if(!props.comma)onError(props.start,"MISSING_CHAR",`Missing , between ${fcName} items`);if(props.comment){let prevItemComment="";loop:for(let st of start)switch(st.type){case"comma":case"space":break;case"comment":prevItemComment=st.source.substring(1);break loop;default:break loop}if(prevItemComment){let prev=coll.items[coll.items.length-1];if(identity.isPair(prev))prev=prev.value??prev.key;if(prev.comment)prev.comment+=`
|
|
3426
3426
|
`+prevItemComment;else prev.comment=prevItemComment;props.comment=props.comment.substring(prevItemComment.length+1)}}}if(!isMap&&!sep2&&!props.found){let valueNode=value?composeNode(ctx,value,props,onError):composeEmptyNode(ctx,props.end,sep2,null,props,onError);if(coll.items.push(valueNode),offset=valueNode.range[2],isBlock(value))onError(valueNode.range,"BLOCK_IN_FLOW",blockMsg)}else{ctx.atKey=!0;let keyStart=props.end,keyNode=key3?composeNode(ctx,key3,props,onError):composeEmptyNode(ctx,keyStart,start,null,props,onError);if(isBlock(key3))onError(keyNode.range,"BLOCK_IN_FLOW",blockMsg);ctx.atKey=!1;let valueProps=resolveProps.resolveProps(sep2??[],{flow:fcName,indicator:"map-value-ind",next:value,offset:keyNode.range[2],onError,parentIndent:fc.indent,startOnNewline:!1});if(valueProps.found){if(!isMap&&!props.found&&ctx.options.strict){if(sep2)for(let st of sep2){if(st===valueProps.found)break;if(st.type==="newline"){onError(st,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(props.start<valueProps.found.offset-1024)onError(valueProps.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(value)if("source"in value&&value.source?.[0]===":")onError(value,"MISSING_CHAR",`Missing space after : in ${fcName}`);else onError(valueProps.start,"MISSING_CHAR",`Missing , or : between ${fcName} items`);let valueNode=value?composeNode(ctx,value,valueProps,onError):valueProps.found?composeEmptyNode(ctx,valueProps.end,sep2,null,valueProps,onError):null;if(valueNode){if(isBlock(value))onError(valueNode.range,"BLOCK_IN_FLOW",blockMsg)}else if(valueProps.comment)if(keyNode.comment)keyNode.comment+=`
|
|
3427
3427
|
`+valueProps.comment;else keyNode.comment=valueProps.comment;let pair=new Pair.Pair(keyNode,valueNode);if(ctx.options.keepSourceTokens)pair.srcToken=collItem;if(isMap){let map=coll;if(utilMapIncludes.mapIncludes(ctx,map.items,keyNode))onError(keyStart,"DUPLICATE_KEY","Map keys must be unique");map.items.push(pair)}else{let map=new YAMLMap.YAMLMap(ctx.schema);map.flow=!0,map.items.push(pair);let endRange=(valueNode??keyNode).range;map.range=[keyNode.range[0],endRange[1],endRange[2]],coll.items.push(map)}offset=valueNode?valueNode.range[2]:valueProps.end}}let expectedEnd=isMap?"}":"]",[ce2,...ee]=fc.end,cePos=offset;if(ce2?.source===expectedEnd)cePos=ce2.offset+ce2.source.length;else{let name=fcName[0].toUpperCase()+fcName.substring(1),msg=atRoot?`${name} must end with a ${expectedEnd}`:`${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;if(onError(offset,atRoot?"MISSING_CHAR":"BAD_INDENT",msg),ce2&&ce2.source.length!==1)ee.unshift(ce2)}if(ee.length>0){let end=resolveEnd.resolveEnd(ee,cePos,ctx.options.strict,onError);if(end.comment)if(coll.comment)coll.comment+=`
|
|
3428
|
-
`+end.comment;else coll.comment=end.comment;coll.range=[fc.offset,cePos,end.offset]}else coll.range=[fc.offset,cePos,cePos];return coll}exports.resolveFlowCollection=resolveFlowCollection});var require_compose_collection=__commonJS((exports)=>{var identity=require_identity(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),resolveBlockMap=require_resolve_block_map(),resolveBlockSeq=require_resolve_block_seq(),resolveFlowCollection=require_resolve_flow_collection();function resolveCollection(CN,ctx,token,onError,tagName,tag){let coll=token.type==="block-map"?resolveBlockMap.resolveBlockMap(CN,ctx,token,onError,tag):token.type==="block-seq"?resolveBlockSeq.resolveBlockSeq(CN,ctx,token,onError,tag):resolveFlowCollection.resolveFlowCollection(CN,ctx,token,onError,tag),Coll=coll.constructor;if(tagName==="!"||tagName===Coll.tagName)return coll.tag=Coll.tagName,coll;if(tagName)coll.tag=tagName;return coll}function composeCollection(CN,ctx,token,props,onError){let tagToken=props.tag,tagName=!tagToken?null:ctx.directives.tagName(tagToken.source,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg));if(token.type==="block-seq"){let{anchor,newlineAfterProp:nl}=props,lastProp=anchor&&tagToken?anchor.offset>tagToken.offset?anchor:tagToken:anchor??tagToken;if(lastProp&&(!nl||nl.offset<lastProp.offset))onError(lastProp,"MISSING_CHAR","Missing newline after block sequence props")}let expType=token.type==="block-map"?"map":token.type==="block-seq"?"seq":token.start.source==="{"?"map":"seq";if(!tagToken||!tagName||tagName==="!"||tagName===YAMLMap.YAMLMap.tagName&&expType==="map"||tagName===YAMLSeq.YAMLSeq.tagName&&expType==="seq")return resolveCollection(CN,ctx,token,onError,tagName);let tag=ctx.schema.tags.find((t2)=>t2.tag===tagName&&t2.collection===expType);if(!tag){let kt=ctx.schema.knownTags[tagName];if(kt?.collection===expType)ctx.schema.tags.push(Object.assign({},kt,{default:!1})),tag=kt;else{if(kt)onError(tagToken,"BAD_COLLECTION_TYPE",`${kt.tag} used for ${expType} collection, but expects ${kt.collection??"scalar"}`,!0);else onError(tagToken,"TAG_RESOLVE_FAILED",`Unresolved tag: ${tagName}`,!0);return resolveCollection(CN,ctx,token,onError,tagName)}}let coll=resolveCollection(CN,ctx,token,onError,tagName,tag),res=tag.resolve?.(coll,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg),ctx.options)??coll,node=identity.isNode(res)?res:new Scalar.Scalar(res);if(node.range=coll.range,node.tag=tagName,tag?.format)node.format=tag.format;return node}exports.composeCollection=composeCollection});var require_resolve_block_scalar=__commonJS((exports)=>{var Scalar=require_Scalar();function resolveBlockScalar(ctx,
|
|
3429
|
-
`.repeat(Math.max(1,lines3.length-1)):"",end2=start+header.length;if(
|
|
3428
|
+
`+end.comment;else coll.comment=end.comment;coll.range=[fc.offset,cePos,end.offset]}else coll.range=[fc.offset,cePos,cePos];return coll}exports.resolveFlowCollection=resolveFlowCollection});var require_compose_collection=__commonJS((exports)=>{var identity=require_identity(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),resolveBlockMap=require_resolve_block_map(),resolveBlockSeq=require_resolve_block_seq(),resolveFlowCollection=require_resolve_flow_collection();function resolveCollection(CN,ctx,token,onError,tagName,tag){let coll=token.type==="block-map"?resolveBlockMap.resolveBlockMap(CN,ctx,token,onError,tag):token.type==="block-seq"?resolveBlockSeq.resolveBlockSeq(CN,ctx,token,onError,tag):resolveFlowCollection.resolveFlowCollection(CN,ctx,token,onError,tag),Coll=coll.constructor;if(tagName==="!"||tagName===Coll.tagName)return coll.tag=Coll.tagName,coll;if(tagName)coll.tag=tagName;return coll}function composeCollection(CN,ctx,token,props,onError){let tagToken=props.tag,tagName=!tagToken?null:ctx.directives.tagName(tagToken.source,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg));if(token.type==="block-seq"){let{anchor,newlineAfterProp:nl}=props,lastProp=anchor&&tagToken?anchor.offset>tagToken.offset?anchor:tagToken:anchor??tagToken;if(lastProp&&(!nl||nl.offset<lastProp.offset))onError(lastProp,"MISSING_CHAR","Missing newline after block sequence props")}let expType=token.type==="block-map"?"map":token.type==="block-seq"?"seq":token.start.source==="{"?"map":"seq";if(!tagToken||!tagName||tagName==="!"||tagName===YAMLMap.YAMLMap.tagName&&expType==="map"||tagName===YAMLSeq.YAMLSeq.tagName&&expType==="seq")return resolveCollection(CN,ctx,token,onError,tagName);let tag=ctx.schema.tags.find((t2)=>t2.tag===tagName&&t2.collection===expType);if(!tag){let kt=ctx.schema.knownTags[tagName];if(kt?.collection===expType)ctx.schema.tags.push(Object.assign({},kt,{default:!1})),tag=kt;else{if(kt)onError(tagToken,"BAD_COLLECTION_TYPE",`${kt.tag} used for ${expType} collection, but expects ${kt.collection??"scalar"}`,!0);else onError(tagToken,"TAG_RESOLVE_FAILED",`Unresolved tag: ${tagName}`,!0);return resolveCollection(CN,ctx,token,onError,tagName)}}let coll=resolveCollection(CN,ctx,token,onError,tagName,tag),res=tag.resolve?.(coll,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg),ctx.options)??coll,node=identity.isNode(res)?res:new Scalar.Scalar(res);if(node.range=coll.range,node.tag=tagName,tag?.format)node.format=tag.format;return node}exports.composeCollection=composeCollection});var require_resolve_block_scalar=__commonJS((exports)=>{var Scalar=require_Scalar();function resolveBlockScalar(ctx,scalar2,onError){let start=scalar2.offset,header=parseBlockScalarHeader(scalar2,ctx.options.strict,onError);if(!header)return{value:"",type:null,comment:"",range:[start,start,start]};let type=header.mode===">"?Scalar.Scalar.BLOCK_FOLDED:Scalar.Scalar.BLOCK_LITERAL,lines3=scalar2.source?splitLines(scalar2.source):[],chompStart=lines3.length;for(let i=lines3.length-1;i>=0;--i){let content=lines3[i][1];if(content===""||content==="\r")chompStart=i;else break}if(chompStart===0){let value2=header.chomp==="+"&&lines3.length>0?`
|
|
3429
|
+
`.repeat(Math.max(1,lines3.length-1)):"",end2=start+header.length;if(scalar2.source)end2+=scalar2.source.length;return{value:value2,type,comment:header.comment,range:[start,end2,end2]}}let trimIndent=scalar2.indent+header.indent,offset=scalar2.offset+header.length,contentStart=0;for(let i=0;i<chompStart;++i){let[indent,content]=lines3[i];if(content===""||content==="\r"){if(header.indent===0&&indent.length>trimIndent)trimIndent=indent.length}else{if(indent.length<trimIndent)onError(offset+indent.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(header.indent===0)trimIndent=indent.length;if(contentStart=i,trimIndent===0&&!ctx.atRoot)onError(offset,"BAD_INDENT","Block scalar values in collections must be indented");break}offset+=indent.length+content.length+1}for(let i=lines3.length-1;i>=chompStart;--i)if(lines3[i][0].length>trimIndent)chompStart=i+1;let value="",sep2="",prevMoreIndented=!1;for(let i=0;i<contentStart;++i)value+=lines3[i][0].slice(trimIndent)+`
|
|
3430
3430
|
`;for(let i=contentStart;i<chompStart;++i){let[indent,content]=lines3[i];offset+=indent.length+content.length+1;let crlf=content[content.length-1]==="\r";if(crlf)content=content.slice(0,-1);if(content&&indent.length<trimIndent){let message=`Block scalar lines must not be less indented than their ${header.indent?"explicit indentation indicator":"first line"}`;onError(offset-content.length-(crlf?2:1),"BAD_INDENT",message),indent=""}if(type===Scalar.Scalar.BLOCK_LITERAL)value+=sep2+indent.slice(trimIndent)+content,sep2=`
|
|
3431
3431
|
`;else if(indent.length>trimIndent||content[0]==="\t"){if(sep2===" ")sep2=`
|
|
3432
3432
|
`;else if(!prevMoreIndented&&sep2===`
|
|
@@ -3440,7 +3440,7 @@ ${pointer}
|
|
|
3440
3440
|
`+lines3[i][0].slice(trimIndent);if(value[value.length-1]!==`
|
|
3441
3441
|
`)value+=`
|
|
3442
3442
|
`;break;default:value+=`
|
|
3443
|
-
`}let end=start+header.length+
|
|
3443
|
+
`}let end=start+header.length+scalar2.source.length;return{value,type,comment:header.comment,range:[start,end,end]}}function parseBlockScalarHeader({offset,props},strict,onError){if(props[0].type!=="block-scalar-header")return onError(props[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source}=props[0],mode=source[0],indent=0,chomp="",error=-1;for(let i=1;i<source.length;++i){let ch=source[i];if(!chomp&&(ch==="-"||ch==="+"))chomp=ch;else{let n=Number(ch);if(!indent&&n)indent=n;else if(error===-1)error=offset+i}}if(error!==-1)onError(error,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${source}`);let hasSpace=!1,comment="",length=source.length;for(let i=1;i<props.length;++i){let token=props[i];switch(token.type){case"space":hasSpace=!0;case"newline":length+=token.source.length;break;case"comment":if(strict&&!hasSpace)onError(token,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");length+=token.source.length,comment=token.source.substring(1);break;case"error":onError(token,"UNEXPECTED_TOKEN",token.message),length+=token.source.length;break;default:{let message=`Unexpected token in block scalar header: ${token.type}`;onError(token,"UNEXPECTED_TOKEN",message);let ts=token.source;if(ts&&typeof ts==="string")length+=ts.length}}}return{mode,indent,chomp,comment,length}}function splitLines(source){let split=source.split(/\n( *)/),first=split[0],m2=first.match(/^( *)/),lines3=[m2?.[1]?[m2[1],first.slice(m2[1].length)]:["",first]];for(let i=1;i<split.length;i+=2)lines3.push([split[i],split[i+1]]);return lines3}exports.resolveBlockScalar=resolveBlockScalar});var require_resolve_flow_scalar=__commonJS((exports)=>{var Scalar=require_Scalar(),resolveEnd=require_resolve_end();function resolveFlowScalar(scalar2,strict,onError){let{offset,type,source,end}=scalar2,_type,value,_onError=(rel2,code,msg)=>onError(offset+rel2,code,msg);switch(type){case"scalar":_type=Scalar.Scalar.PLAIN,value=plainValue(source,_onError);break;case"single-quoted-scalar":_type=Scalar.Scalar.QUOTE_SINGLE,value=singleQuotedValue(source,_onError);break;case"double-quoted-scalar":_type=Scalar.Scalar.QUOTE_DOUBLE,value=doubleQuotedValue(source,_onError);break;default:return onError(scalar2,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${type}`),{value:"",type:null,comment:"",range:[offset,offset+source.length,offset+source.length]}}let valueEnd=offset+source.length,re2=resolveEnd.resolveEnd(end,valueEnd,strict,onError);return{value,type:_type,comment:re2.comment,range:[offset,valueEnd,re2.offset]}}function plainValue(source,onError){let badChar="";switch(source[0]){case"\t":badChar="a tab character";break;case",":badChar="flow indicator character ,";break;case"%":badChar="directive indicator character %";break;case"|":case">":{badChar=`block scalar indicator ${source[0]}`;break}case"@":case"`":{badChar=`reserved character ${source[0]}`;break}}if(badChar)onError(0,"BAD_SCALAR_START",`Plain value cannot start with ${badChar}`);return foldLines(source)}function singleQuotedValue(source,onError){if(source[source.length-1]!=="'"||source.length===1)onError(source.length,"MISSING_CHAR","Missing closing 'quote");return foldLines(source.slice(1,-1)).replace(/''/g,"'")}function foldLines(source){let first,line;try{first=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
3444
3444
|
`,"sy"),line=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
3445
3445
|
`,"sy")}catch{first=/(.*?)[ \t]*\r?\n/sy,line=/[ \t]*(.*?)[ \t]*\r?\n/sy}let match2=first.exec(source);if(!match2)return source;let res=match2[1],sep2=" ",pos=first.lastIndex;line.lastIndex=pos;while(match2=line.exec(source)){if(match2[1]==="")if(sep2===`
|
|
3446
3446
|
`)res+=sep2;else sep2=`
|
|
@@ -3455,7 +3455,7 @@ ${pointer}
|
|
|
3455
3455
|
`)break;if(ch===`
|
|
3456
3456
|
`)fold+=`
|
|
3457
3457
|
`;offset+=1,ch=source[offset+1]}if(!fold)fold=" ";return{fold,offset}}var escapeCodes={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
3458
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function parseCharCode(source,offset,length,onError){let cc=source.substr(offset,length),code=cc.length===length&&/^[0-9a-fA-F]+$/.test(cc)?parseInt(cc,16):NaN;try{return String.fromCodePoint(code)}catch{let raw=source.substr(offset-2,length+2);return onError(offset-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${raw}`),raw}}exports.resolveFlowScalar=resolveFlowScalar});var require_compose_scalar=__commonJS((exports)=>{var identity=require_identity(),Scalar=require_Scalar(),resolveBlockScalar=require_resolve_block_scalar(),resolveFlowScalar=require_resolve_flow_scalar();function composeScalar(ctx,token,tagToken,onError){let{value,type,comment,range}=token.type==="block-scalar"?resolveBlockScalar.resolveBlockScalar(ctx,token,onError):resolveFlowScalar.resolveFlowScalar(token,ctx.options.strict,onError),tagName=tagToken?ctx.directives.tagName(tagToken.source,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg)):null,tag;if(ctx.options.stringKeys&&ctx.atKey)tag=ctx.schema[identity.SCALAR];else if(tagName)tag=findScalarTagByName(ctx.schema,value,tagName,tagToken,onError);else if(token.type==="scalar")tag=findScalarTagByTest(ctx,value,token,onError);else tag=ctx.schema[identity.SCALAR];let
|
|
3458
|
+
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function parseCharCode(source,offset,length,onError){let cc=source.substr(offset,length),code=cc.length===length&&/^[0-9a-fA-F]+$/.test(cc)?parseInt(cc,16):NaN;try{return String.fromCodePoint(code)}catch{let raw=source.substr(offset-2,length+2);return onError(offset-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${raw}`),raw}}exports.resolveFlowScalar=resolveFlowScalar});var require_compose_scalar=__commonJS((exports)=>{var identity=require_identity(),Scalar=require_Scalar(),resolveBlockScalar=require_resolve_block_scalar(),resolveFlowScalar=require_resolve_flow_scalar();function composeScalar(ctx,token,tagToken,onError){let{value,type,comment,range}=token.type==="block-scalar"?resolveBlockScalar.resolveBlockScalar(ctx,token,onError):resolveFlowScalar.resolveFlowScalar(token,ctx.options.strict,onError),tagName=tagToken?ctx.directives.tagName(tagToken.source,(msg)=>onError(tagToken,"TAG_RESOLVE_FAILED",msg)):null,tag;if(ctx.options.stringKeys&&ctx.atKey)tag=ctx.schema[identity.SCALAR];else if(tagName)tag=findScalarTagByName(ctx.schema,value,tagName,tagToken,onError);else if(token.type==="scalar")tag=findScalarTagByTest(ctx,value,token,onError);else tag=ctx.schema[identity.SCALAR];let scalar2;try{let res=tag.resolve(value,(msg)=>onError(tagToken??token,"TAG_RESOLVE_FAILED",msg),ctx.options);scalar2=identity.isScalar(res)?res:new Scalar.Scalar(res)}catch(error){let msg=error instanceof Error?error.message:String(error);onError(tagToken??token,"TAG_RESOLVE_FAILED",msg),scalar2=new Scalar.Scalar(value)}if(scalar2.range=range,scalar2.source=value,type)scalar2.type=type;if(tagName)scalar2.tag=tagName;if(tag.format)scalar2.format=tag.format;if(comment)scalar2.comment=comment;return scalar2}function findScalarTagByName(schema,value,tagName,tagToken,onError){if(tagName==="!")return schema[identity.SCALAR];let matchWithTest=[];for(let tag of schema.tags)if(!tag.collection&&tag.tag===tagName)if(tag.default&&tag.test)matchWithTest.push(tag);else return tag;for(let tag of matchWithTest)if(tag.test?.test(value))return tag;let kt=schema.knownTags[tagName];if(kt&&!kt.collection)return schema.tags.push(Object.assign({},kt,{default:!1,test:void 0})),kt;return onError(tagToken,"TAG_RESOLVE_FAILED",`Unresolved tag: ${tagName}`,tagName!=="tag:yaml.org,2002:str"),schema[identity.SCALAR]}function findScalarTagByTest({atKey,directives,schema},value,token,onError){let tag=schema.tags.find((tag2)=>(tag2.default===!0||atKey&&tag2.default==="key")&&tag2.test?.test(value))||schema[identity.SCALAR];if(schema.compat){let compat=schema.compat.find((tag2)=>tag2.default&&tag2.test?.test(value))??schema[identity.SCALAR];if(tag.tag!==compat.tag){let ts=directives.tagString(tag.tag),cs=directives.tagString(compat.tag),msg=`Value may be parsed as either ${ts} or ${cs}`;onError(token,"TAG_RESOLVE_FAILED",msg,!0)}}return tag}exports.composeScalar=composeScalar});var require_util_empty_scalar_position=__commonJS((exports)=>{function emptyScalarPosition(offset,before,pos){if(before){pos??(pos=before.length);for(let i=pos-1;i>=0;--i){let st=before[i];switch(st.type){case"space":case"comment":case"newline":offset-=st.source.length;continue}st=before[++i];while(st?.type==="space")offset+=st.source.length,st=before[++i];break}}return offset}exports.emptyScalarPosition=emptyScalarPosition});var require_compose_node=__commonJS((exports)=>{var Alias=require_Alias(),identity=require_identity(),composeCollection=require_compose_collection(),composeScalar=require_compose_scalar(),resolveEnd=require_resolve_end(),utilEmptyScalarPosition=require_util_empty_scalar_position(),CN={composeNode,composeEmptyNode};function composeNode(ctx,token,props,onError){let atKey=ctx.atKey,{spaceBefore,comment,anchor,tag}=props,node,isSrcToken=!0;switch(token.type){case"alias":if(node=composeAlias(ctx,token,onError),anchor||tag)onError(token,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(node=composeScalar.composeScalar(ctx,token,tag,onError),anchor)node.anchor=anchor.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(node=composeCollection.composeCollection(CN,ctx,token,props,onError),anchor)node.anchor=anchor.source.substring(1)}catch(error){let message=error instanceof Error?error.message:String(error);onError(token,"RESOURCE_EXHAUSTION",message)}break;default:{let message=token.type==="error"?token.message:`Unsupported token (type: ${token.type})`;onError(token,"UNEXPECTED_TOKEN",message),isSrcToken=!1}}if(node??(node=composeEmptyNode(ctx,token.offset,void 0,null,props,onError)),anchor&&node.anchor==="")onError(anchor,"BAD_ALIAS","Anchor cannot be an empty string");if(atKey&&ctx.options.stringKeys&&(!identity.isScalar(node)||typeof node.value!=="string"||node.tag&&node.tag!=="tag:yaml.org,2002:str"))onError(tag??token,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(spaceBefore)node.spaceBefore=!0;if(comment)if(token.type==="scalar"&&token.source==="")node.comment=comment;else node.commentBefore=comment;if(ctx.options.keepSourceTokens&&isSrcToken)node.srcToken=token;return node}function composeEmptyNode(ctx,offset,before,pos,{spaceBefore,comment,anchor,tag,end},onError){let token={type:"scalar",offset:utilEmptyScalarPosition.emptyScalarPosition(offset,before,pos),indent:-1,source:""},node=composeScalar.composeScalar(ctx,token,tag,onError);if(anchor){if(node.anchor=anchor.source.substring(1),node.anchor==="")onError(anchor,"BAD_ALIAS","Anchor cannot be an empty string")}if(spaceBefore)node.spaceBefore=!0;if(comment)node.comment=comment,node.range[2]=end;return node}function composeAlias({options},{offset,source,end},onError){let alias=new Alias.Alias(source.substring(1));if(alias.source==="")onError(offset,"BAD_ALIAS","Alias cannot be an empty string");if(alias.source.endsWith(":"))onError(offset+source.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let valueEnd=offset+source.length,re2=resolveEnd.resolveEnd(end,valueEnd,options.strict,onError);if(alias.range=[offset,valueEnd,re2.offset],re2.comment)alias.comment=re2.comment;return alias}exports.composeEmptyNode=composeEmptyNode;exports.composeNode=composeNode});var require_compose_doc=__commonJS((exports)=>{var Document=require_Document(),composeNode=require_compose_node(),resolveEnd=require_resolve_end(),resolveProps=require_resolve_props();function composeDoc(options,directives,{offset,start,value,end},onError){let opts=Object.assign({_directives:directives},options),doc=new Document.Document(void 0,opts),ctx={atKey:!1,atRoot:!0,directives:doc.directives,options:doc.options,schema:doc.schema},props=resolveProps.resolveProps(start,{indicator:"doc-start",next:value??end?.[0],offset,onError,parentIndent:0,startOnNewline:!0});if(props.found){if(doc.directives.docStart=!0,value&&(value.type==="block-map"||value.type==="block-seq")&&!props.hasNewline)onError(props.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}doc.contents=value?composeNode.composeNode(ctx,value,props,onError):composeNode.composeEmptyNode(ctx,props.end,start,null,props,onError);let contentEnd=doc.contents.range[2],re2=resolveEnd.resolveEnd(end,contentEnd,!1,onError);if(re2.comment)doc.comment=re2.comment;return doc.range=[offset,contentEnd,re2.offset],doc}exports.composeDoc=composeDoc});var require_composer=__commonJS((exports)=>{var node_process=__require("process"),directives=require_directives(),Document=require_Document(),errors=require_errors(),identity=require_identity(),composeDoc=require_compose_doc(),resolveEnd=require_resolve_end();function getErrorPos(src){if(typeof src==="number")return[src,src+1];if(Array.isArray(src))return src.length===2?src:[src[0],src[1]];let{offset,source}=src;return[offset,offset+(typeof source==="string"?source.length:1)]}function parsePrelude(prelude){let comment="",atComment=!1,afterEmptyLine=!1;for(let i=0;i<prelude.length;++i){let source=prelude[i];switch(source[0]){case"#":comment+=(comment===""?"":afterEmptyLine?`
|
|
3459
3459
|
|
|
3460
3460
|
`:`
|
|
3461
3461
|
`)+(source.substring(1)||" "),atComment=!0,afterEmptyLine=!1;break;case"%":if(prelude[i+1]?.[0]!=="#")i+=1;atComment=!1;break;default:if(!atComment)afterEmptyLine=!0;atComment=!1}}return{comment,afterEmptyLine}}class Composer{constructor(options={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(source,code,message,warning)=>{let pos=getErrorPos(source);if(warning)this.warnings.push(new errors.YAMLWarning(pos,code,message));else this.errors.push(new errors.YAMLParseError(pos,code,message))},this.directives=new directives.Directives({version:options.version||"1.2"}),this.options=options}decorate(doc,afterDoc){let{comment,afterEmptyLine}=parsePrelude(this.prelude);if(comment){let dc=doc.contents;if(afterDoc)doc.comment=doc.comment?`${doc.comment}
|
|
@@ -3491,7 +3491,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
3491
3491
|
`,next=this.buffer[i+1];else end=i;if(next==="#"||inFlow&&flowIndicatorChars.has(next))break;if(ch===`
|
|
3492
3492
|
`){let cs=this.continueScalar(i+1);if(cs===-1)break;i=Math.max(i,cs-2)}}else{if(inFlow&&flowIndicatorChars.has(ch))break;end=i}if(!ch&&!this.atEnd)return this.setNext("plain-scalar");return yield cst.SCALAR,yield*this.pushToIndex(end+1,!0),inFlow?"flow":"doc"}*pushCount(n){if(n>0)return yield this.buffer.substr(this.pos,n),this.pos+=n,n;return 0}*pushToIndex(i,allowEmpty){let s=this.buffer.slice(this.pos,i);if(s)return yield s,this.pos+=s.length,s.length;else if(allowEmpty)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(isNotAnchorChar))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let inFlow=this.flowLevel>0,ch1=this.charAt(1);if(isEmpty(ch1)||inFlow&&flowIndicatorChars.has(ch1)){if(!inFlow)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;return(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let i=this.pos+2,ch=this.buffer[i];while(!isEmpty(ch)&&ch!==">")ch=this.buffer[++i];return yield*this.pushToIndex(ch===">"?i+1:i,!1)}else{let i=this.pos+1,ch=this.buffer[i];while(ch)if(tagChars.has(ch))ch=this.buffer[++i];else if(ch==="%"&&hexDigits.has(this.buffer[i+1])&&hexDigits.has(this.buffer[i+2]))ch=this.buffer[i+=3];else break;return yield*this.pushToIndex(i,!1)}}*pushNewline(){let ch=this.buffer[this.pos];if(ch===`
|
|
3493
3493
|
`)return yield*this.pushCount(1);else if(ch==="\r"&&this.charAt(1)===`
|
|
3494
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces(allowTabs){let i=this.pos-1,ch;do ch=this.buffer[++i];while(ch===" "||allowTabs&&ch==="\t");let n=i-this.pos;if(n>0)yield this.buffer.substr(this.pos,n),this.pos=i;return n}*pushUntil(test){let i=this.pos,ch=this.buffer[i];while(!test(ch))ch=this.buffer[++i];return yield*this.pushToIndex(i,!1)}}exports.Lexer=Lexer});var require_line_counter=__commonJS((exports)=>{class LineCounter{constructor(){this.lineStarts=[],this.addNewLine=(offset)=>this.lineStarts.push(offset),this.linePos=(offset)=>{let low=0,high=this.lineStarts.length;while(low<high){let mid2=low+high>>1;if(this.lineStarts[mid2]<offset)low=mid2+1;else high=mid2}if(this.lineStarts[low]===offset)return{line:low+1,col:1};if(low===0)return{line:0,col:offset};let start=this.lineStarts[low-1];return{line:low,col:offset-start+1}}}}exports.LineCounter=LineCounter});var require_parser=__commonJS((exports)=>{var node_process=__require("process"),cst=require_cst(),lexer=require_lexer();function includesToken(list2,type){for(let i=0;i<list2.length;++i)if(list2[i].type===type)return!0;return!1}function findNonEmptyIndex(list2){for(let i=0;i<list2.length;++i)switch(list2[i].type){case"space":case"comment":case"newline":break;default:return i}return-1}function isFlowToken(token){switch(token?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function getPrevProps(parent2){switch(parent2.type){case"document":return parent2.start;case"block-map":{let it=parent2.items[parent2.items.length-1];return it.sep??it.start}case"block-seq":return parent2.items[parent2.items.length-1].start;default:return[]}}function getFirstKeyStartProps(prev){if(prev.length===0)return[];let i=prev.length;loop:while(--i>=0)switch(prev[i].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break loop}while(prev[++i]?.type==="space");return prev.splice(i,prev.length)}function fixFlowSeqItems(fc){if(fc.start.type==="flow-seq-start"){for(let it of fc.items)if(it.sep&&!it.value&&!includesToken(it.start,"explicit-key-ind")&&!includesToken(it.sep,"map-value-ind")){if(it.key)it.value=it.key;if(delete it.key,isFlowToken(it.value))if(it.value.end)Array.prototype.push.apply(it.value.end,it.sep);else it.value.end=it.sep;else Array.prototype.push.apply(it.start,it.sep);delete it.sep}}}class Parser{constructor(onNewLine){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new lexer.Lexer,this.onNewLine=onNewLine}*parse(source,incomplete=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let lexeme of this.lexer.lex(source,incomplete))yield*this.next(lexeme);if(!incomplete)yield*this.end()}*next(source){if(this.source=source,node_process.env.LOG_TOKENS)console.log("|",cst.prettyToken(source));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=source.length;return}let type=cst.tokenType(source);if(!type){let message=`Not a YAML token: ${source}`;yield*this.pop({type:"error",offset:this.offset,message,source}),this.offset+=source.length}else if(type==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=type,yield*this.step(),type){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+source.length);break;case"space":if(this.atNewLine&&source[0]===" ")this.indent+=source.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=source.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=source.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let top=this.peek(1);if(this.type==="doc-end"&&top?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!top)return yield*this.stream();switch(top.type){case"document":return yield*this.document(top);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(top);case"block-scalar":return yield*this.blockScalar(top);case"block-map":return yield*this.blockMap(top);case"block-seq":return yield*this.blockSequence(top);case"flow-collection":return yield*this.flowCollection(top);case"doc-end":return yield*this.documentEnd(top)}yield*this.pop()}peek(n){return this.stack[this.stack.length-n]}*pop(error){let token=error??this.stack.pop();if(!token)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield token;else{let top=this.peek(1);if(token.type==="block-scalar")token.indent="indent"in top?top.indent:0;else if(token.type==="flow-collection"&&top.type==="document")token.indent=0;if(token.type==="flow-collection")fixFlowSeqItems(token);switch(top.type){case"document":top.value=token;break;case"block-scalar":top.props.push(token);break;case"block-map":{let it=top.items[top.items.length-1];if(it.value){top.items.push({start:[],key:token,sep:[]}),this.onKeyLine=!0;return}else if(it.sep)it.value=token;else{Object.assign(it,{key:token,sep:[]}),this.onKeyLine=!it.explicitKey;return}break}case"block-seq":{let it=top.items[top.items.length-1];if(it.value)top.items.push({start:[],value:token});else it.value=token;break}case"flow-collection":{let it=top.items[top.items.length-1];if(!it||it.value)top.items.push({start:[],key:token,sep:[]});else if(it.sep)it.value=token;else Object.assign(it,{key:token,sep:[]});return}default:yield*this.pop(),yield*this.pop(token)}if((top.type==="document"||top.type==="block-map"||top.type==="block-seq")&&(token.type==="block-map"||token.type==="block-seq")){let last=token.items[token.items.length-1];if(last&&!last.sep&&!last.value&&last.start.length>0&&findNonEmptyIndex(last.start)===-1&&(token.indent===0||last.start.every((st)=>st.type!=="comment"||st.indent<token.indent))){if(top.type==="document")top.end=last.start;else top.items.push({start:last.start});token.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let doc={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")doc.start.push(this.sourceToken);this.stack.push(doc);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(doc){if(doc.value)return yield*this.lineEnd(doc);switch(this.type){case"doc-start":{if(findNonEmptyIndex(doc.start)!==-1)yield*this.pop(),yield*this.step();else doc.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":doc.start.push(this.sourceToken);return}let bv=this.startBlockValue(doc);if(bv)this.stack.push(bv);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(
|
|
3494
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces(allowTabs){let i=this.pos-1,ch;do ch=this.buffer[++i];while(ch===" "||allowTabs&&ch==="\t");let n=i-this.pos;if(n>0)yield this.buffer.substr(this.pos,n),this.pos=i;return n}*pushUntil(test){let i=this.pos,ch=this.buffer[i];while(!test(ch))ch=this.buffer[++i];return yield*this.pushToIndex(i,!1)}}exports.Lexer=Lexer});var require_line_counter=__commonJS((exports)=>{class LineCounter{constructor(){this.lineStarts=[],this.addNewLine=(offset)=>this.lineStarts.push(offset),this.linePos=(offset)=>{let low=0,high=this.lineStarts.length;while(low<high){let mid2=low+high>>1;if(this.lineStarts[mid2]<offset)low=mid2+1;else high=mid2}if(this.lineStarts[low]===offset)return{line:low+1,col:1};if(low===0)return{line:0,col:offset};let start=this.lineStarts[low-1];return{line:low,col:offset-start+1}}}}exports.LineCounter=LineCounter});var require_parser=__commonJS((exports)=>{var node_process=__require("process"),cst=require_cst(),lexer=require_lexer();function includesToken(list2,type){for(let i=0;i<list2.length;++i)if(list2[i].type===type)return!0;return!1}function findNonEmptyIndex(list2){for(let i=0;i<list2.length;++i)switch(list2[i].type){case"space":case"comment":case"newline":break;default:return i}return-1}function isFlowToken(token){switch(token?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function getPrevProps(parent2){switch(parent2.type){case"document":return parent2.start;case"block-map":{let it=parent2.items[parent2.items.length-1];return it.sep??it.start}case"block-seq":return parent2.items[parent2.items.length-1].start;default:return[]}}function getFirstKeyStartProps(prev){if(prev.length===0)return[];let i=prev.length;loop:while(--i>=0)switch(prev[i].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break loop}while(prev[++i]?.type==="space");return prev.splice(i,prev.length)}function fixFlowSeqItems(fc){if(fc.start.type==="flow-seq-start"){for(let it of fc.items)if(it.sep&&!it.value&&!includesToken(it.start,"explicit-key-ind")&&!includesToken(it.sep,"map-value-ind")){if(it.key)it.value=it.key;if(delete it.key,isFlowToken(it.value))if(it.value.end)Array.prototype.push.apply(it.value.end,it.sep);else it.value.end=it.sep;else Array.prototype.push.apply(it.start,it.sep);delete it.sep}}}class Parser{constructor(onNewLine){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new lexer.Lexer,this.onNewLine=onNewLine}*parse(source,incomplete=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let lexeme of this.lexer.lex(source,incomplete))yield*this.next(lexeme);if(!incomplete)yield*this.end()}*next(source){if(this.source=source,node_process.env.LOG_TOKENS)console.log("|",cst.prettyToken(source));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=source.length;return}let type=cst.tokenType(source);if(!type){let message=`Not a YAML token: ${source}`;yield*this.pop({type:"error",offset:this.offset,message,source}),this.offset+=source.length}else if(type==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=type,yield*this.step(),type){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+source.length);break;case"space":if(this.atNewLine&&source[0]===" ")this.indent+=source.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=source.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=source.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let top=this.peek(1);if(this.type==="doc-end"&&top?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!top)return yield*this.stream();switch(top.type){case"document":return yield*this.document(top);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(top);case"block-scalar":return yield*this.blockScalar(top);case"block-map":return yield*this.blockMap(top);case"block-seq":return yield*this.blockSequence(top);case"flow-collection":return yield*this.flowCollection(top);case"doc-end":return yield*this.documentEnd(top)}yield*this.pop()}peek(n){return this.stack[this.stack.length-n]}*pop(error){let token=error??this.stack.pop();if(!token)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield token;else{let top=this.peek(1);if(token.type==="block-scalar")token.indent="indent"in top?top.indent:0;else if(token.type==="flow-collection"&&top.type==="document")token.indent=0;if(token.type==="flow-collection")fixFlowSeqItems(token);switch(top.type){case"document":top.value=token;break;case"block-scalar":top.props.push(token);break;case"block-map":{let it=top.items[top.items.length-1];if(it.value){top.items.push({start:[],key:token,sep:[]}),this.onKeyLine=!0;return}else if(it.sep)it.value=token;else{Object.assign(it,{key:token,sep:[]}),this.onKeyLine=!it.explicitKey;return}break}case"block-seq":{let it=top.items[top.items.length-1];if(it.value)top.items.push({start:[],value:token});else it.value=token;break}case"flow-collection":{let it=top.items[top.items.length-1];if(!it||it.value)top.items.push({start:[],key:token,sep:[]});else if(it.sep)it.value=token;else Object.assign(it,{key:token,sep:[]});return}default:yield*this.pop(),yield*this.pop(token)}if((top.type==="document"||top.type==="block-map"||top.type==="block-seq")&&(token.type==="block-map"||token.type==="block-seq")){let last=token.items[token.items.length-1];if(last&&!last.sep&&!last.value&&last.start.length>0&&findNonEmptyIndex(last.start)===-1&&(token.indent===0||last.start.every((st)=>st.type!=="comment"||st.indent<token.indent))){if(top.type==="document")top.end=last.start;else top.items.push({start:last.start});token.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let doc={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")doc.start.push(this.sourceToken);this.stack.push(doc);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(doc){if(doc.value)return yield*this.lineEnd(doc);switch(this.type){case"doc-start":{if(findNonEmptyIndex(doc.start)!==-1)yield*this.pop(),yield*this.step();else doc.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":doc.start.push(this.sourceToken);return}let bv=this.startBlockValue(doc);if(bv)this.stack.push(bv);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(scalar2){if(this.type==="map-value-ind"){let prev=getPrevProps(this.peek(2)),start=getFirstKeyStartProps(prev),sep2;if(scalar2.end)sep2=scalar2.end,sep2.push(this.sourceToken),delete scalar2.end;else sep2=[this.sourceToken];let map={type:"block-map",offset:scalar2.offset,indent:scalar2.indent,items:[{start,key:scalar2,sep:sep2}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map}else yield*this.lineEnd(scalar2)}*blockScalar(scalar2){switch(this.type){case"space":case"comment":case"newline":scalar2.props.push(this.sourceToken);return;case"scalar":if(scalar2.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let nl=this.source.indexOf(`
|
|
3495
3495
|
`)+1;while(nl!==0)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
|
|
3496
3496
|
`,nl)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(map){let it=map.items[map.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,it.value){let end="end"in it.value?it.value.end:void 0;if((Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment")end?.push(this.sourceToken);else map.items.push({start:[this.sourceToken]})}else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"space":case"comment":if(it.value)map.items.push({start:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else{if(this.atIndentedComment(it.start,map.indent)){let end=map.items[map.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it.start),end.push(this.sourceToken),map.items.pop();return}}it.start.push(this.sourceToken)}return}if(this.indent>=map.indent){let atMapIndent=!this.onKeyLine&&this.indent===map.indent,atNextItem=atMapIndent&&(it.sep||it.explicitKey)&&this.type!=="seq-item-ind",start=[];if(atNextItem&&it.sep&&!it.value){let nl=[];for(let i=0;i<it.sep.length;++i){let st=it.sep[i];switch(st.type){case"newline":nl.push(i);break;case"space":break;case"comment":if(st.indent>map.indent)nl.length=0;break;default:nl.length=0}}if(nl.length>=2)start=it.sep.splice(nl[1])}switch(this.type){case"anchor":case"tag":if(atNextItem||it.value)start.push(this.sourceToken),map.items.push({start}),this.onKeyLine=!0;else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"explicit-key-ind":if(!it.sep&&!it.explicitKey)it.start.push(this.sourceToken),it.explicitKey=!0;else if(atNextItem||it.value)start.push(this.sourceToken),map.items.push({start,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(it.explicitKey)if(!it.sep)if(includesToken(it.start,"newline"))Object.assign(it,{key:null,sep:[this.sourceToken]});else{let start2=getFirstKeyStartProps(it.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}else if(it.value)map.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(it.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(it.key)&&!includesToken(it.sep,"newline")){let start2=getFirstKeyStartProps(it.start),key3=it.key,sep2=it.sep;sep2.push(this.sourceToken),delete it.key,delete it.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:key3,sep:sep2}]})}else if(start.length>0)it.sep=it.sep.concat(start,this.sourceToken);else it.sep.push(this.sourceToken);else if(!it.sep)Object.assign(it,{key:null,sep:[this.sourceToken]});else if(it.value||atNextItem)map.items.push({start,key:null,sep:[this.sourceToken]});else if(includesToken(it.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else it.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs7=this.flowScalar(this.type);if(atNextItem||it.value)map.items.push({start,key:fs7,sep:[]}),this.onKeyLine=!0;else if(it.sep)this.stack.push(fs7);else Object.assign(it,{key:fs7,sep:[]}),this.onKeyLine=!0;return}default:{let bv=this.startBlockValue(map);if(bv){if(bv.type==="block-seq"){if(!it.explicitKey&&it.sep&&!includesToken(it.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(atMapIndent)map.items.push({start});this.stack.push(bv);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(seq){let it=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it.value){let end="end"in it.value?it.value.end:void 0;if((Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment")end?.push(this.sourceToken);else seq.items.push({start:[this.sourceToken]})}else it.start.push(this.sourceToken);return;case"space":case"comment":if(it.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it.start,seq.indent)){let end=seq.items[seq.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it.start),end.push(this.sourceToken),seq.items.pop();return}}it.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it.value||this.indent<=seq.indent)break;it.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;if(it.value||includesToken(it.start,"seq-item-ind"))seq.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return}if(this.indent>seq.indent){let bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop(),yield*this.step()}*flowCollection(fc){let it=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do yield*this.pop(),top=this.peek(1);while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!it||it.sep)fc.items.push({start:[this.sourceToken]});else it.start.push(this.sourceToken);return;case"map-value-ind":if(!it||it.value)fc.items.push({start:[],key:null,sep:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else Object.assign(it,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!it||it.value)fc.items.push({start:[this.sourceToken]});else if(it.sep)it.sep.push(this.sourceToken);else it.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs7=this.flowScalar(this.type);if(!it||it.value)fc.items.push({start:[],key:fs7,sep:[]});else if(it.sep)this.stack.push(fs7);else Object.assign(it,{key:fs7,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}let bv=this.startBlockValue(fc);if(bv)this.stack.push(bv);else yield*this.pop(),yield*this.step()}else{let parent2=this.peek(2);if(parent2.type==="block-map"&&(this.type==="map-value-ind"&&parent2.indent===fc.indent||this.type==="newline"&&!parent2.items[parent2.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&parent2.type!=="flow-collection"){let prev=getPrevProps(parent2),start=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);let sep2=fc.end.splice(1,fc.end.length);sep2.push(this.sourceToken);let map={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep2}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map}else yield*this.lineEnd(fc)}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
|
|
3497
3497
|
`)+1;while(nl!==0)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
|
|
@@ -3664,9 +3664,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
3664
3664
|
`));break;default:if("tokens"in token&&Array.isArray(token.tokens))this.renderInlineContent(token.tokens,chunks);else if("text"in token&&typeof token.text==="string")chunks.push(this.createDefaultChunk(token.text));break}}renderInlineTokenWithStyle(token,chunks,styleGroup,link2){switch(token.type){case"text":chunks.push(this.createChunk(token.text,styleGroup,link2));break;case"escape":chunks.push(this.createChunk(token.text,styleGroup,link2));break;case"codespan":if(this._conceal)chunks.push(this.createChunk(token.text,"markup.raw",link2));else chunks.push(this.createChunk("`","markup.raw",link2)),chunks.push(this.createChunk(token.text,"markup.raw",link2)),chunks.push(this.createChunk("`","markup.raw",link2));break;default:this.renderInlineToken(token,chunks);break}}applyMargins(renderable,marginTop,marginBottom){renderable.marginTop=marginTop,renderable.marginBottom=marginBottom}createMarkdownCodeRenderable(content,id,marginBottom=0){return new CodeRenderable(this.ctx,{id,content,filetype:"markdown",syntaxStyle:this._syntaxStyle,fg:this._fg,bg:this._bg,conceal:this._conceal,drawUnstyledText:!1,streaming:!0,onChunks:this._linkifyMarkdownChunks,treeSitterClient:this._treeSitterClient,width:"100%",marginBottom})}createCodeRenderable(token,id,marginBottom=0){return new CodeRenderable(this.ctx,{id,content:token.text,filetype:infoStringToFiletype(token.lang??""),syntaxStyle:this._syntaxStyle,fg:this._fg,bg:this._bg,conceal:this._concealCode,drawUnstyledText:!(this._streaming&&this._concealCode),streaming:this._streaming,treeSitterClient:this._treeSitterClient,width:"100%",marginBottom})}applyMarkdownCodeRenderable(renderable,content,marginBottom){renderable.content=content,renderable.filetype="markdown",renderable.syntaxStyle=this._syntaxStyle,renderable.fg=this._fg,renderable.bg=this._bg,renderable.conceal=this._conceal,renderable.drawUnstyledText=!1,renderable.streaming=!0,renderable.marginBottom=marginBottom}applyCodeBlockRenderable(renderable,token,marginBottom){renderable.content=token.text,renderable.filetype=infoStringToFiletype(token.lang??""),renderable.syntaxStyle=this._syntaxStyle,renderable.fg=this._fg,renderable.bg=this._bg,renderable.conceal=this._concealCode,renderable.drawUnstyledText=!(this._streaming&&this._concealCode),renderable.streaming=this._streaming,renderable.marginBottom=marginBottom}shouldRenderSeparately(token){return token.type==="code"||token.type==="table"||token.type==="blockquote"}getInterBlockMargin(token,hasNextToken){if(!hasNextToken)return 0;return this.shouldRenderSeparately(token)?1:0}createMarkdownBlockToken(raw){return{type:"paragraph",raw,text:raw,tokens:[]}}normalizeMarkdownBlockRaw(raw){return raw.replace(TRAILING_MARKDOWN_BLOCK_BREAKS_RE,`
|
|
3665
3665
|
`)}normalizeScrollbackMarkdownBlockRaw(raw){return raw.replace(TRAILING_MARKDOWN_BLOCK_NEWLINES_RE,"")}buildRenderableTokens(tokens){if(this._renderNode)return tokens.filter((token)=>token.type!=="space");let renderTokens=[],markdownRaw="",flushMarkdownRaw=()=>{if(markdownRaw.length===0)return;let normalizedRaw=this.normalizeMarkdownBlockRaw(markdownRaw);if(normalizedRaw.length>0)renderTokens.push(this.createMarkdownBlockToken(normalizedRaw));markdownRaw=""};for(let i=0;i<tokens.length;i+=1){let token=tokens[i];if(token.type==="space"){if(markdownRaw.length===0)continue;let nextIndex=i+1;while(nextIndex<tokens.length&&tokens[nextIndex].type==="space")nextIndex+=1;let nextToken=tokens[nextIndex];if(nextToken&&!this.shouldRenderSeparately(nextToken))markdownRaw+=token.raw;continue}if(this.shouldRenderSeparately(token)){flushMarkdownRaw(),renderTokens.push(token);continue}markdownRaw+=token.raw}return flushMarkdownRaw(),renderTokens}buildTopLevelRenderBlocks(tokens){let blocks=[],gapBefore="";for(let i=0;i<tokens.length;i+=1){let token=tokens[i];if(token.type==="space"){gapBefore+=token.raw;continue}let prev=blocks[blocks.length-1],marginTop=prev&&(this.shouldRenderSeparately(prev.token)||TRAILING_MARKDOWN_BLOCK_BREAKS_RE.test(prev.token.raw+gapBefore))?1:0;blocks.push({token,sourceTokenEnd:i+1,marginTop}),gapBefore=""}return blocks}getTableRowsToRender(table){return table.rows}hashString(value,seed){let hash=seed>>>0;for(let i=0;i<value.length;i+=1)hash^=value.charCodeAt(i),hash=Math.imul(hash,16777619);return hash>>>0}hashTableToken(token,seed,depth=0){let hash=this.hashString(token.type,seed);if("raw"in token&&typeof token.raw==="string")return this.hashString(token.raw,hash);if("text"in token&&typeof token.text==="string")hash=this.hashString(token.text,hash);if(depth<2&&"tokens"in token&&Array.isArray(token.tokens))for(let child of token.tokens)hash=this.hashTableToken(child,hash,depth+1);return hash>>>0}getTableCellKey(cell,isHeader){let seed=isHeader?2902232141:1371922141;if(!cell)return seed;if(typeof cell.text==="string")return this.hashString(cell.text,seed);if(Array.isArray(cell.tokens)&&cell.tokens.length>0){let hash=seed^cell.tokens.length;for(let token of cell.tokens)hash=this.hashTableToken(token,hash);return hash>>>0}return(seed^2654435769)>>>0}createTableDataCellChunks(cell){let chunks=[];if(cell)this.renderInlineContent(cell.tokens,chunks);return chunks.length>0?chunks:[this.createDefaultChunk(" ")]}createTableHeaderCellChunks(cell){let chunks=[];this.renderInlineContent(cell.tokens,chunks);let baseChunks=chunks.length>0?chunks:[this.createDefaultChunk(" ")],headingStyle=this.getStyle("markup.heading")||this.getStyle("default");if(!headingStyle)return baseChunks;let headingAttributes=createTextAttributes({bold:headingStyle.bold,italic:headingStyle.italic,underline:headingStyle.underline,dim:headingStyle.dim});return baseChunks.map((chunk)=>({...chunk,fg:headingStyle.fg??chunk.fg,bg:headingStyle.bg??chunk.bg,attributes:headingAttributes}))}buildTableContentCache(table,previous,forceRegenerate=!1){let colCount=table.header.length,rowsToRender=this.getTableRowsToRender(table);if(colCount===0||rowsToRender.length===0)return{cache:null,changed:previous!==void 0};let content=[],cellKeys=[],totalRows=rowsToRender.length+1,changed=forceRegenerate||!previous;for(let rowIndex=0;rowIndex<totalRows;rowIndex+=1){let rowContent=[],rowKeys=new Uint32Array(colCount);for(let colIndex=0;colIndex<colCount;colIndex+=1){let isHeader=rowIndex===0,cell=isHeader?table.header[colIndex]:rowsToRender[rowIndex-1]?.[colIndex],cellKey=this.getTableCellKey(cell,isHeader);rowKeys[colIndex]=cellKey;let previousCellKey=previous?.cellKeys[rowIndex]?.[colIndex],previousCellContent=previous?.content[rowIndex]?.[colIndex];if(!forceRegenerate&&previousCellKey===cellKey&&Array.isArray(previousCellContent)){rowContent.push(previousCellContent);continue}changed=!0,rowContent.push(isHeader?this.createTableHeaderCellChunks(table.header[colIndex]):this.createTableDataCellChunks(cell))}content.push(rowContent),cellKeys.push(rowKeys)}if(previous&&!changed){if(previous.content.length!==content.length)changed=!0;else for(let rowIndex=0;rowIndex<content.length;rowIndex+=1)if((previous.content[rowIndex]?.length??0)!==content[rowIndex].length){changed=!0;break}}return{cache:{content,cellKeys},changed}}resolveTableStyle(options=this._tableOptions){if(options?.style==="columns")return"columns";if(options?.style==="grid")return"grid";return this._internalBlockMode==="top-level"?"columns":"grid"}usesBorderlessColumnSpacing(options=this._tableOptions){let style=this.resolveTableStyle(options),borders=options?.borders??style==="grid";return style==="columns"&&!borders}resolveTableRenderableOptions(){let style=this.resolveTableStyle(),borders=this._tableOptions?.borders??style==="grid";return{columnWidthMode:this._tableOptions?.widthMode??(style==="columns"?"content":"full"),columnFitter:this._tableOptions?.columnFitter??"proportional",wrapMode:this._tableOptions?.wrapMode??"word",cellPadding:this._tableOptions?.cellPadding??0,columnGap:this.usesBorderlessColumnSpacing()?2:0,border:borders,outerBorder:this._tableOptions?.outerBorder??borders,showBorders:borders,borderStyle:this._tableOptions?.borderStyle??"single",borderColor:this._tableOptions?.borderColor??this.getStyle("conceal")?.fg??"#888888",selectable:this._tableOptions?.selectable??!0}}applyTableRenderableOptions(tableRenderable,options){tableRenderable.columnWidthMode=options.columnWidthMode,tableRenderable.columnFitter=options.columnFitter,tableRenderable.wrapMode=options.wrapMode,tableRenderable.cellPadding=options.cellPadding,tableRenderable.columnGap=options.columnGap,tableRenderable.border=options.border,tableRenderable.outerBorder=options.outerBorder,tableRenderable.showBorders=options.showBorders,tableRenderable.borderStyle=options.borderStyle,tableRenderable.borderColor=options.borderColor,tableRenderable.selectable=options.selectable}applyTableOptionsToBlocks(){let options=this.resolveTableRenderableOptions(),updated=!1;for(let state of this._blockStates)if(state.renderable instanceof TextTableRenderable)this.applyTableRenderableOptions(state.renderable,options),updated=!0;if(updated)this.requestRender()}createTextTableRenderable(content,id,marginBottom=0){let options=this.resolveTableRenderableOptions();return new TextTableRenderable(this.ctx,{id,content,width:"100%",marginBottom,columnWidthMode:options.columnWidthMode,columnFitter:options.columnFitter,wrapMode:options.wrapMode,cellPadding:options.cellPadding,columnGap:options.columnGap,border:options.border,outerBorder:options.outerBorder,showBorders:options.showBorders,borderStyle:options.borderStyle,borderColor:options.borderColor,selectable:options.selectable})}createTableBlock(table,id,marginBottom=0,previousCache,forceRegenerate=!1){let{cache}=this.buildTableContentCache(table,previousCache,forceRegenerate);if(!cache)return{renderable:this.createMarkdownCodeRenderable(table.raw,id,marginBottom)};return{renderable:this.createTextTableRenderable(cache.content,id,marginBottom),tableContentCache:cache}}getStableBlockCount(blocks,stableTokenCount){if(this._internalBlockMode!=="top-level")return 0;let stableBlockCount=0;for(let block of blocks){if(block.sourceTokenEnd<=stableTokenCount){stableBlockCount+=1;continue}break}return stableBlockCount}syncTopLevelBlockState(state,block,tableContentCache=state.tableContentCache){state.token=block.token,state.tokenRaw=block.token.raw,state.marginTop=block.marginTop,state.tableContentCache=tableContentCache}getTopLevelBlockRaw(token){if(!token.raw)return;return this.shouldRenderSeparately(token)?token.raw:this.normalizeScrollbackMarkdownBlockRaw(token.raw)}createTopLevelDefaultRenderable(block,index){let{token,marginTop}=block,id=`${this.id}-block-${index}`;if(token.type==="code"){let renderable2=this.createCodeRenderable(token,id);return renderable2.marginTop=marginTop,{renderable:renderable2}}if(token.type==="table"){let next=this.createTableBlock(token,id);return next.renderable.marginTop=marginTop,next}let markdownRaw=this.getTopLevelBlockRaw(token);if(!markdownRaw)return{renderable:void 0};let renderable=this.createMarkdownCodeRenderable(markdownRaw,id);return renderable.marginTop=marginTop,{renderable}}createTopLevelRenderable(block,index){if(!this._renderNode)return this.createTopLevelDefaultRenderable(block,index);let next,context={syntaxStyle:this._syntaxStyle,conceal:this._conceal,concealCode:this._concealCode,treeSitterClient:this._treeSitterClient,defaultRender:()=>{return next=this.createTopLevelDefaultRenderable(block,index),next.renderable??null}},custom=this._renderNode(block.token,context);if(custom)return this.applyMargins(custom,block.marginTop,0),{renderable:custom};return next??this.createTopLevelDefaultRenderable(block,index)}createDefaultRenderable(token,index,hasNextToken=!1){let id=`${this.id}-block-${index}`,marginBottom=this.getInterBlockMargin(token,hasNextToken);if(token.type==="code")return this.createCodeRenderable(token,id,marginBottom);if(token.type==="table")return this.createTableBlock(token,id,marginBottom).renderable;if(token.type==="space")return null;if(!token.raw)return null;return this.createMarkdownCodeRenderable(token.raw,id,marginBottom)}updateBlockRenderable(state,token,index,hasNextToken){let marginBottom=this.getInterBlockMargin(token,hasNextToken);if(token.type==="code"){this.applyCodeBlockRenderable(state.renderable,token,marginBottom);return}if(token.type==="table"){let tableToken=token,{cache,changed}=this.buildTableContentCache(tableToken,state.tableContentCache);if(!cache){if(state.renderable instanceof CodeRenderable){this.applyMarkdownCodeRenderable(state.renderable,tableToken.raw,marginBottom),state.tableContentCache=void 0;return}state.renderable.destroyRecursively();let fallbackRenderable=this.createMarkdownCodeRenderable(tableToken.raw,`${this.id}-block-${index}`,marginBottom);this.add(fallbackRenderable),state.renderable=fallbackRenderable,state.tableContentCache=void 0;return}if(state.renderable instanceof TextTableRenderable){if(changed)state.renderable.content=cache.content;this.applyTableRenderableOptions(state.renderable,this.resolveTableRenderableOptions()),state.renderable.marginBottom=marginBottom,state.tableContentCache=cache;return}state.renderable.destroyRecursively();let tableRenderable=this.createTextTableRenderable(cache.content,`${this.id}-block-${index}`,marginBottom);this.add(tableRenderable),state.renderable=tableRenderable,state.tableContentCache=cache;return}if(state.renderable instanceof CodeRenderable){this.applyMarkdownCodeRenderable(state.renderable,token.raw,marginBottom);return}state.renderable.destroyRecursively();let markdownRenderable=this.createMarkdownCodeRenderable(token.raw,`${this.id}-block-${index}`,marginBottom);this.add(markdownRenderable),state.renderable=markdownRenderable}updateTopLevelBlocks(tokens,forceTableRefresh){let blocks=this.buildTopLevelRenderBlocks(tokens);this._stableBlockCount=this.getStableBlockCount(blocks,this._parseState?.stableTokenCount??0);let blockIndex=0;for(let i=0;i<blocks.length;i+=1){let block=blocks[i],existing=this._blockStates[blockIndex];if(existing&&existing.token===block.token&&!forceTableRefresh){if(existing.marginTop!==block.marginTop)this.applyMargins(existing.renderable,block.marginTop,0);this.syncTopLevelBlockState(existing,block),blockIndex++;continue}if(existing&&existing.tokenRaw===block.token.raw&&existing.token.type===block.token.type&&!forceTableRefresh){if(existing.marginTop!==block.marginTop)this.applyMargins(existing.renderable,block.marginTop,0);this.syncTopLevelBlockState(existing,block),blockIndex++;continue}if(existing)existing.renderable.destroyRecursively();let next=this.createTopLevelRenderable(block,blockIndex);if(next.renderable)this.add(next.renderable),this._blockStates[blockIndex]={token:block.token,tokenRaw:block.token.raw,marginTop:block.marginTop,renderable:next.renderable,tableContentCache:next.tableContentCache};blockIndex++}while(this._blockStates.length>blockIndex)this._blockStates.pop().renderable.destroyRecursively()}updateBlocks(forceTableRefresh=!1){if(this.isDestroyed)return;if(!this._content){this.clearBlockStates(),this._parseState=null,this._stableBlockCount=0;return}let trailingUnstable=this._streaming?2:0;this._parseState=parseMarkdownIncremental(this._content,this._parseState,trailingUnstable);let tokens=this._parseState.tokens;if(tokens.length===0&&this._content.length>0){this.clearBlockStates(),this._stableBlockCount=0;let fallback=this.createMarkdownCodeRenderable(this._content,`${this.id}-fallback`);this.add(fallback),this._blockStates=[{token:{type:"text",raw:this._content,text:this._content},tokenRaw:this._content,marginTop:0,renderable:fallback}];return}if(this._internalBlockMode==="top-level"){this.updateTopLevelBlocks(tokens,forceTableRefresh);return}this._stableBlockCount=0;let blockTokens=this.buildRenderableTokens(tokens),lastBlockIndex=blockTokens.length-1,blockIndex=0;for(let i=0;i<blockTokens.length;i++){let token=blockTokens[i],hasNextToken=i<lastBlockIndex,existing=this._blockStates[blockIndex],shouldForceRefresh=forceTableRefresh;if(existing&&existing.token===token){if(shouldForceRefresh)this.updateBlockRenderable(existing,token,blockIndex,hasNextToken),existing.tokenRaw=token.raw;blockIndex++;continue}if(existing&&existing.tokenRaw===token.raw&&existing.token.type===token.type){if(existing.token=token,shouldForceRefresh)this.updateBlockRenderable(existing,token,blockIndex,hasNextToken),existing.tokenRaw=token.raw;blockIndex++;continue}if(existing&&existing.token.type===token.type){this.updateBlockRenderable(existing,token,blockIndex,hasNextToken),existing.token=token,existing.tokenRaw=token.raw,blockIndex++;continue}if(existing)existing.renderable.destroyRecursively();let renderable,tableContentCache;if(this._renderNode){let context={syntaxStyle:this._syntaxStyle,conceal:this._conceal,concealCode:this._concealCode,treeSitterClient:this._treeSitterClient,defaultRender:()=>this.createDefaultRenderable(token,blockIndex,hasNextToken)},custom=this._renderNode(token,context);if(custom)renderable=custom}if(!renderable)if(token.type==="table"){let tableBlock=this.createTableBlock(token,`${this.id}-block-${blockIndex}`,this.getInterBlockMargin(token,hasNextToken));renderable=tableBlock.renderable,tableContentCache=tableBlock.tableContentCache}else renderable=this.createDefaultRenderable(token,blockIndex,hasNextToken)??void 0;if(token.type==="table"&&!tableContentCache&&renderable instanceof TextTableRenderable){let{cache}=this.buildTableContentCache(token);tableContentCache=cache??void 0}if(renderable)this.add(renderable),this._blockStates[blockIndex]={token,tokenRaw:token.raw,renderable,tableContentCache};blockIndex++}while(this._blockStates.length>blockIndex)this._blockStates.pop().renderable.destroyRecursively()}clearBlockStates(){for(let state of this._blockStates)state.renderable.destroyRecursively();this._blockStates=[],this._stableBlockCount=0}rerenderBlocks(){if(this._internalBlockMode==="top-level"){this.updateBlocks(!0);return}for(let i=0;i<this._blockStates.length;i++){let state=this._blockStates[i],hasNextToken=i<this._blockStates.length-1,marginBottom=this.getInterBlockMargin(state.token,hasNextToken);if(state.token.type==="code"){this.applyCodeBlockRenderable(state.renderable,state.token,marginBottom);continue}if(state.token.type==="table"){let tableToken=state.token,{cache}=this.buildTableContentCache(tableToken,state.tableContentCache,!0);if(!cache){if(state.renderable instanceof CodeRenderable)this.applyMarkdownCodeRenderable(state.renderable,tableToken.raw,marginBottom);else{state.renderable.destroyRecursively();let fallbackRenderable=this.createMarkdownCodeRenderable(tableToken.raw,`${this.id}-block-${i}`,marginBottom);this.add(fallbackRenderable),state.renderable=fallbackRenderable}state.tableContentCache=void 0;continue}if(state.renderable instanceof TextTableRenderable){state.renderable.content=cache.content,this.applyTableRenderableOptions(state.renderable,this.resolveTableRenderableOptions()),state.renderable.marginBottom=marginBottom,state.tableContentCache=cache;continue}state.renderable.destroyRecursively();let tableRenderable=this.createTextTableRenderable(cache.content,`${this.id}-block-${i}`,marginBottom);this.add(tableRenderable),state.renderable=tableRenderable,state.tableContentCache=cache;continue}if(state.renderable instanceof CodeRenderable){this.applyMarkdownCodeRenderable(state.renderable,state.token.raw,marginBottom);continue}state.renderable.destroyRecursively();let markdownRenderable=this.createMarkdownCodeRenderable(state.token.raw,`${this.id}-block-${i}`,marginBottom);this.add(markdownRenderable),state.renderable=markdownRenderable}}clearCache(){this._parseState=null,this.clearBlockStates(),this.updateBlocks(),this.requestRender()}refreshStyles(){this._styleDirty=!1,this.rerenderBlocks(),this.requestRender()}renderSelf(buffer,deltaTime){if(this._styleDirty)this._styleDirty=!1,this.rerenderBlocks();super.renderSelf(buffer,deltaTime)}}var defaultThumbBackgroundColor=RGBA.fromHex("#9a9ea3"),defaultTrackBackgroundColor=RGBA.fromHex("#252527");class SliderRenderable extends Renderable{orientation;_value;_min;_max;_viewPortSize;_backgroundColor;_foregroundColor;_onChange;constructor(ctx,options){super(ctx,{flexShrink:0,...options});this.orientation=options.orientation,this._min=options.min??0,this._max=options.max??100,this._value=options.value??this._min,this._viewPortSize=options.viewPortSize??Math.max(1,(this._max-this._min)*0.1),this._onChange=options.onChange,this._backgroundColor=options.backgroundColor?parseColor(options.backgroundColor):defaultTrackBackgroundColor,this._foregroundColor=options.foregroundColor?parseColor(options.foregroundColor):defaultThumbBackgroundColor,this.setupMouseHandling()}get value(){return this._value}set value(newValue){let clamped=Math.max(this._min,Math.min(this._max,newValue));if(clamped!==this._value)this._value=clamped,this._onChange?.(clamped),this.emit("change",{value:clamped}),this.requestRender()}get min(){return this._min}set min(newMin){if(newMin!==this._min){if(this._min=newMin,this._value<newMin)this.value=newMin;this.requestRender()}}get max(){return this._max}set max(newMax){if(newMax!==this._max){if(this._max=newMax,this._value>newMax)this.value=newMax;this.requestRender()}}set viewPortSize(size){let clampedSize=Math.max(0.01,Math.min(size,this._max-this._min));if(clampedSize!==this._viewPortSize)this._viewPortSize=clampedSize,this.requestRender()}get viewPortSize(){return this._viewPortSize}get backgroundColor(){return this._backgroundColor}set backgroundColor(value){this._backgroundColor=parseColor(value),this.requestRender()}get foregroundColor(){return this._foregroundColor}set foregroundColor(value){this._foregroundColor=parseColor(value),this.requestRender()}calculateDragOffsetVirtual(event){let trackStart=this.orientation==="vertical"?this.y:this.x,mousePos=(this.orientation==="vertical"?event.y:event.x)-trackStart,virtualMousePos=Math.max(0,Math.min((this.orientation==="vertical"?this.height:this.width)*2,mousePos*2)),virtualThumbStart=this.getVirtualThumbStart(),virtualThumbSize=this.getVirtualThumbSize();return Math.max(0,Math.min(virtualThumbSize,virtualMousePos-virtualThumbStart))}setupMouseHandling(){let isDragging=!1,dragOffsetVirtual=0;this.onMouseDown=(event)=>{event.stopPropagation(),event.preventDefault();let thumb=this.getThumbRect();if(event.x>=thumb.x&&event.x<thumb.x+thumb.width&&event.y>=thumb.y&&event.y<thumb.y+thumb.height)isDragging=!0,dragOffsetVirtual=this.calculateDragOffsetVirtual(event);else this.updateValueFromMouseDirect(event),isDragging=!0,dragOffsetVirtual=this.calculateDragOffsetVirtual(event)},this.onMouseDrag=(event)=>{if(!isDragging)return;event.stopPropagation(),this.updateValueFromMouseWithOffset(event,dragOffsetVirtual)},this.onMouseUp=(event)=>{if(isDragging)this.updateValueFromMouseWithOffset(event,dragOffsetVirtual);isDragging=!1}}updateValueFromMouseDirect(event){let trackStart=this.orientation==="vertical"?this.y:this.x,trackSize=this.orientation==="vertical"?this.height:this.width,relativeMousePos=(this.orientation==="vertical"?event.y:event.x)-trackStart,clampedMousePos=Math.max(0,Math.min(trackSize,relativeMousePos)),ratio=trackSize===0?0:clampedMousePos/trackSize,range=this._max-this._min,newValue=this._min+ratio*range;this.value=newValue}updateValueFromMouseWithOffset(event,offsetVirtual){let trackStart=this.orientation==="vertical"?this.y:this.x,trackSize=this.orientation==="vertical"?this.height:this.width,mousePos=this.orientation==="vertical"?event.y:event.x,virtualTrackSize=trackSize*2,relativeMousePos=mousePos-trackStart,virtualMousePos=Math.max(0,Math.min(trackSize,relativeMousePos))*2,virtualThumbSize=this.getVirtualThumbSize(),maxThumbStart=Math.max(0,virtualTrackSize-virtualThumbSize),desiredThumbStart=virtualMousePos-offsetVirtual;desiredThumbStart=Math.max(0,Math.min(maxThumbStart,desiredThumbStart));let ratio=maxThumbStart===0?0:desiredThumbStart/maxThumbStart,range=this._max-this._min,newValue=this._min+ratio*range;this.value=newValue}getThumbRect(){let virtualThumbSize=this.getVirtualThumbSize(),virtualThumbStart=this.getVirtualThumbStart(),realThumbStart=Math.floor(virtualThumbStart/2),realThumbSize=Math.ceil((virtualThumbStart+virtualThumbSize)/2)-realThumbStart;if(this.orientation==="vertical")return{x:this.x,y:this.y+realThumbStart,width:this.width,height:Math.max(1,realThumbSize)};else return{x:this.x+realThumbStart,y:this.y,width:Math.max(1,realThumbSize),height:this.height}}renderSelf(buffer){if(this.orientation==="horizontal")this.renderHorizontal(buffer);else this.renderVertical(buffer)}renderHorizontal(buffer){let virtualThumbSize=this.getVirtualThumbSize(),virtualThumbStart=this.getVirtualThumbStart(),virtualThumbEnd=virtualThumbStart+virtualThumbSize;buffer.fillRect(this.x,this.y,this.width,this.height,this._backgroundColor);let realStartCell=Math.floor(virtualThumbStart/2),realEndCell=Math.ceil(virtualThumbEnd/2)-1,startX=Math.max(0,realStartCell),endX=Math.min(this.width-1,realEndCell);for(let realX=startX;realX<=endX;realX++){let virtualCellStart=realX*2,virtualCellEnd=virtualCellStart+2,thumbStartInCell=Math.max(virtualThumbStart,virtualCellStart),coverage=Math.min(virtualThumbEnd,virtualCellEnd)-thumbStartInCell,char=" ";if(coverage>=2)char="\u2588";else if(thumbStartInCell===virtualCellStart)char="\u258C";else char="\u2590";for(let y2=0;y2<this.height;y2++)buffer.setCellWithAlphaBlending(this.x+realX,this.y+y2,char,this._foregroundColor,this._backgroundColor)}}renderVertical(buffer){let virtualThumbSize=this.getVirtualThumbSize(),virtualThumbStart=this.getVirtualThumbStart(),virtualThumbEnd=virtualThumbStart+virtualThumbSize;buffer.fillRect(this.x,this.y,this.width,this.height,this._backgroundColor);let realStartCell=Math.floor(virtualThumbStart/2),realEndCell=Math.ceil(virtualThumbEnd/2)-1,startY=Math.max(0,realStartCell),endY=Math.min(this.height-1,realEndCell);for(let realY=startY;realY<=endY;realY++){let virtualCellStart=realY*2,virtualCellEnd=virtualCellStart+2,thumbStartInCell=Math.max(virtualThumbStart,virtualCellStart),coverage=Math.min(virtualThumbEnd,virtualCellEnd)-thumbStartInCell,char=" ";if(coverage>=2)char="\u2588";else if(coverage>0)if(thumbStartInCell-virtualCellStart===0)char="\u2580";else char="\u2584";for(let x2=0;x2<this.width;x2++)buffer.setCellWithAlphaBlending(this.x+x2,this.y+realY,char,this._foregroundColor,this._backgroundColor)}}getVirtualThumbSize(){let virtualTrackSize=this.orientation==="vertical"?this.height*2:this.width*2,range=this._max-this._min;if(range===0)return virtualTrackSize;let viewportSize=Math.max(1,this._viewPortSize),contentSize=range+viewportSize;if(contentSize<=viewportSize)return virtualTrackSize;let thumbRatio=viewportSize/contentSize,calculatedSize=Math.floor(virtualTrackSize*thumbRatio);return Math.max(1,Math.min(calculatedSize,virtualTrackSize))}getVirtualThumbStart(){let virtualTrackSize=this.orientation==="vertical"?this.height*2:this.width*2,range=this._max-this._min;if(range===0)return 0;let valueRatio=(this._value-this._min)/range,virtualThumbSize=this.getVirtualThumbSize();return Math.round(valueRatio*(virtualTrackSize-virtualThumbSize))}}class ScrollBarRenderable extends Renderable{slider;startArrow;endArrow;orientation;_focusable=!0;_scrollSize=0;_scrollPosition=0;_viewportSize=0;_showArrows=!1;_manualVisibility=!1;_onChange;scrollStep=null;get visible(){return super.visible}set visible(value){this._manualVisibility=!0,super.visible=value}resetVisibilityControl(){this._manualVisibility=!1,this.recalculateVisibility()}get scrollSize(){return this._scrollSize}get scrollPosition(){return this._scrollPosition}get viewportSize(){return this._viewportSize}set scrollSize(value){if(value===this.scrollSize)return;this._scrollSize=value,this.recalculateVisibility(),this.updateSliderFromScrollState(),this.scrollPosition=this.scrollPosition}set scrollPosition(value){let newPosition=Math.round(Math.min(Math.max(0,value),this.scrollSize-this.viewportSize));if(newPosition!==this._scrollPosition)this._scrollPosition=newPosition,this.updateSliderFromScrollState()}set viewportSize(value){if(value===this.viewportSize)return;this._viewportSize=value,this.slider.viewPortSize=Math.max(1,this._viewportSize),this.recalculateVisibility(),this.updateSliderFromScrollState(),this.scrollPosition=this.scrollPosition}get showArrows(){return this._showArrows}set showArrows(value){if(value===this._showArrows)return;this._showArrows=value,this.startArrow.visible=value,this.endArrow.visible=value}constructor(ctx,{trackOptions,arrowOptions,orientation,showArrows=!1,...options}){super(ctx,{flexDirection:orientation==="vertical"?"column":"row",alignSelf:"stretch",alignItems:"stretch",...options});this._onChange=options.onChange,this.orientation=orientation,this._showArrows=showArrows;let scrollRange=Math.max(0,this._scrollSize-this._viewportSize),defaultStepSize=Math.max(1,this._viewportSize),stepSize=trackOptions?.viewPortSize??defaultStepSize;this.slider=new SliderRenderable(ctx,{orientation,min:0,max:scrollRange,value:this._scrollPosition,viewPortSize:stepSize,onChange:(value)=>{this._scrollPosition=Math.round(value),this._onChange?.(this._scrollPosition),this.emit("change",{position:this._scrollPosition})},...orientation==="vertical"?{width:Math.max(1,Math.min(2,this.width)),height:"100%",marginLeft:"auto"}:{width:"100%",height:1,marginTop:"auto"},flexGrow:1,flexShrink:1,...trackOptions}),this.updateSliderFromScrollState();let arrowOpts=arrowOptions?{foregroundColor:arrowOptions.backgroundColor,backgroundColor:arrowOptions.backgroundColor,attributes:arrowOptions.attributes,...arrowOptions}:{};this.startArrow=new ArrowRenderable(ctx,{alignSelf:"center",visible:this.showArrows,direction:this.orientation==="vertical"?"up":"left",height:this.orientation==="vertical"?1:1,...arrowOpts}),this.endArrow=new ArrowRenderable(ctx,{alignSelf:"center",visible:this.showArrows,direction:this.orientation==="vertical"?"down":"right",height:this.orientation==="vertical"?1:1,...arrowOpts}),this.add(this.startArrow),this.add(this.slider),this.add(this.endArrow);let startArrowMouseTimeout=void 0,endArrowMouseTimeout=void 0;this.startArrow.onMouseDown=(event)=>{event.stopPropagation(),event.preventDefault(),this.scrollBy(-0.5,"viewport"),startArrowMouseTimeout=setTimeout(()=>{this.scrollBy(-0.5,"viewport"),startArrowMouseTimeout=setInterval(()=>{this.scrollBy(-0.2,"viewport")},200)},500)},this.startArrow.onMouseUp=(event)=>{event.stopPropagation(),clearInterval(startArrowMouseTimeout)},this.endArrow.onMouseDown=(event)=>{event.stopPropagation(),event.preventDefault(),this.scrollBy(0.5,"viewport"),endArrowMouseTimeout=setTimeout(()=>{this.scrollBy(0.5,"viewport"),endArrowMouseTimeout=setInterval(()=>{this.scrollBy(0.2,"viewport")},200)},500)},this.endArrow.onMouseUp=(event)=>{event.stopPropagation(),clearInterval(endArrowMouseTimeout)}}set arrowOptions(options){Object.assign(this.startArrow,options),Object.assign(this.endArrow,options),this.requestRender()}set trackOptions(options){Object.assign(this.slider,options),this.requestRender()}updateSliderFromScrollState(){let scrollRange=Math.max(0,this._scrollSize-this._viewportSize);this.slider.min=0,this.slider.max=scrollRange,this.slider.value=Math.min(this._scrollPosition,scrollRange)}scrollBy(delta,unit="absolute"){let resolvedDelta=(unit==="viewport"?this.viewportSize:unit==="content"?this.scrollSize:unit==="step"?this.scrollStep??1:1)*delta;this.scrollPosition+=resolvedDelta}recalculateVisibility(){if(!this._manualVisibility){let sizeRatio=this.scrollSize<=this.viewportSize?1:this.viewportSize/this.scrollSize;super.visible=sizeRatio<1}}handleKeyPress(key){switch(key.name){case"left":case"h":if(this.orientation!=="horizontal")return!1;return this.scrollBy(-0.2,"viewport"),!0;case"right":case"l":if(this.orientation!=="horizontal")return!1;return this.scrollBy(0.2,"viewport"),!0;case"up":case"k":if(this.orientation!=="vertical")return!1;return this.scrollBy(-0.2,"viewport"),!0;case"down":case"j":if(this.orientation!=="vertical")return!1;return this.scrollBy(0.2,"viewport"),!0;case"pageup":return this.scrollBy(-0.5,"viewport"),!0;case"pagedown":return this.scrollBy(0.5,"viewport"),!0;case"home":return this.scrollBy(-1,"content"),!0;case"end":return this.scrollBy(1,"content"),!0}return!1}}class ArrowRenderable extends Renderable{_direction;_foregroundColor;_backgroundColor;_attributes;_arrowChars;constructor(ctx,options){super(ctx,options);if(this._direction=options.direction,this._foregroundColor=options.foregroundColor?parseColor(options.foregroundColor):RGBA.fromValues(1,1,1,1),this._backgroundColor=options.backgroundColor?parseColor(options.backgroundColor):RGBA.fromValues(0,0,0,0),this._attributes=options.attributes??0,this._arrowChars={up:"\u25B2",down:"\u25BC",left:"\u25C0",right:"\u25B6",...options.arrowChars},!options.width)this.width=Bun.stringWidth(this.getArrowChar())}get direction(){return this._direction}set direction(value){if(this._direction!==value)this._direction=value,this.requestRender()}get foregroundColor(){return this._foregroundColor}set foregroundColor(value){if(this._foregroundColor!==value)this._foregroundColor=parseColor(value),this.requestRender()}get backgroundColor(){return this._backgroundColor}set backgroundColor(value){if(this._backgroundColor!==value)this._backgroundColor=parseColor(value),this.requestRender()}get attributes(){return this._attributes}set attributes(value){if(this._attributes!==value)this._attributes=value,this.requestRender()}set arrowChars(value){this._arrowChars={...this._arrowChars,...value},this.requestRender()}renderSelf(buffer){let char=this.getArrowChar();buffer.drawText(char,this.x,this.y,this._foregroundColor,this._backgroundColor,this._attributes)}getArrowChar(){switch(this._direction){case"up":return this._arrowChars.up;case"down":return this._arrowChars.down;case"left":return this._arrowChars.left;case"right":return this._arrowChars.right;default:return"?"}}}class ContentRenderable extends BoxRenderable{viewport;_viewportCulling;constructor(ctx,viewport,viewportCulling,options){super(ctx,options);this.viewport=viewport,this._viewportCulling=viewportCulling}get viewportCulling(){return this._viewportCulling}set viewportCulling(value){this._viewportCulling=value}_hasVisibleChildFilter(){return this._viewportCulling}_getVisibleChildren(){if(this._viewportCulling)return getObjectsInViewport({x:this.viewport.screenX,y:this.viewport.screenY,width:this.viewport.width,height:this.viewport.height},this.getChildrenSortedByPrimaryAxis(),this.primaryAxis,0).map((child)=>child.num);return super._getVisibleChildren()}}var SCROLLBOX_PADDING_KEYS=["padding","paddingX","paddingY","paddingTop","paddingRight","paddingBottom","paddingLeft"];function pickScrollBoxPadding(options){if(!options)return{};let picked={};for(let key of SCROLLBOX_PADDING_KEYS){let value=options[key];if(value!==void 0)picked[key]=value}return picked}function stripScrollBoxPadding(options){let sanitized={...options};for(let key of SCROLLBOX_PADDING_KEYS)delete sanitized[key];return sanitized}class ScrollBoxRenderable extends BoxRenderable{static idCounter=0;internalId=0;wrapper;viewport;content;horizontalScrollBar;verticalScrollBar;_focusable=!0;selectionListener;autoScrollMouseX=0;autoScrollMouseY=0;autoScrollThresholdVertical=3;autoScrollThresholdHorizontal=3;autoScrollSpeedSlow=6;autoScrollSpeedMedium=36;autoScrollSpeedFast=72;isAutoScrolling=!1;cachedAutoScrollSpeed=3;autoScrollAccumulatorX=0;autoScrollAccumulatorY=0;scrollAccumulatorX=0;scrollAccumulatorY=0;_stickyScroll;_stickyScrollTop=!1;_stickyScrollBottom=!1;_stickyScrollLeft=!1;_stickyScrollRight=!1;_stickyStart;_hasManualScroll=!1;_isApplyingStickyScroll=!1;scrollAccel;get stickyScroll(){return this._stickyScroll}set stickyScroll(value){this._stickyScroll=value,this.updateStickyState()}get stickyStart(){return this._stickyStart}set stickyStart(value){this._stickyStart=value,this.updateStickyState()}get scrollTop(){return this.verticalScrollBar.scrollPosition}set scrollTop(value){if(this.verticalScrollBar.scrollPosition=value,!this._isApplyingStickyScroll){let maxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height);if(!this.isAtStickyPosition()&&maxScrollTop>1)this._hasManualScroll=!0}this.updateStickyState()}get scrollLeft(){return this.horizontalScrollBar.scrollPosition}set scrollLeft(value){if(this.horizontalScrollBar.scrollPosition=value,!this._isApplyingStickyScroll){let maxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);if(!this.isAtStickyPosition()&&maxScrollLeft>1)this._hasManualScroll=!0}this.updateStickyState()}get scrollWidth(){return this.horizontalScrollBar.scrollSize}get scrollHeight(){return this.verticalScrollBar.scrollSize}updateStickyState(){if(!this._stickyScroll)return;let maxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height),maxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);if(this.scrollTop<=0){if(this._stickyScrollTop=!0,this._stickyScrollBottom=!1,!this._isApplyingStickyScroll&&(this._stickyStart==="top"||this._stickyStart==="bottom"&&maxScrollTop===0))this._hasManualScroll=!1}else if(this.scrollTop>=maxScrollTop){if(this._stickyScrollTop=!1,this._stickyScrollBottom=!0,!this._isApplyingStickyScroll&&this._stickyStart==="bottom")this._hasManualScroll=!1}else this._stickyScrollTop=!1,this._stickyScrollBottom=!1;if(this.scrollLeft<=0){if(this._stickyScrollLeft=!0,this._stickyScrollRight=!1,!this._isApplyingStickyScroll&&(this._stickyStart==="left"||this._stickyStart==="right"&&maxScrollLeft===0))this._hasManualScroll=!1}else if(this.scrollLeft>=maxScrollLeft){if(this._stickyScrollLeft=!1,this._stickyScrollRight=!0,!this._isApplyingStickyScroll&&this._stickyStart==="right")this._hasManualScroll=!1}else this._stickyScrollLeft=!1,this._stickyScrollRight=!1}applyStickyStart(stickyStart){let wasApplyingStickyScroll=this._isApplyingStickyScroll;this._isApplyingStickyScroll=!0;try{switch(stickyStart){case"top":this._stickyScrollTop=!0,this._stickyScrollBottom=!1,this.verticalScrollBar.scrollPosition=0;break;case"bottom":this._stickyScrollTop=!1,this._stickyScrollBottom=!0,this.verticalScrollBar.scrollPosition=Math.max(0,this.scrollHeight-this.viewport.height);break;case"left":this._stickyScrollLeft=!0,this._stickyScrollRight=!1,this.horizontalScrollBar.scrollPosition=0;break;case"right":this._stickyScrollLeft=!1,this._stickyScrollRight=!0,this.horizontalScrollBar.scrollPosition=Math.max(0,this.scrollWidth-this.viewport.width);break}}finally{this._isApplyingStickyScroll=wasApplyingStickyScroll}}constructor(ctx,options){let{wrapperOptions,viewportOptions,contentOptions,rootOptions,scrollbarOptions,verticalScrollbarOptions,horizontalScrollbarOptions,stickyScroll=!1,stickyStart,scrollX=!1,scrollY=!0,scrollAcceleration,viewportCulling=!0,...rootBoxOptions}=options,forwardedContentPadding={...pickScrollBoxPadding(rootBoxOptions),...pickScrollBoxPadding(rootOptions)},sanitizedRootBoxOptions=stripScrollBoxPadding(rootBoxOptions),sanitizedRootOptions=rootOptions?stripScrollBoxPadding(rootOptions):void 0,mergedContentOptions={...forwardedContentPadding,...contentOptions};super(ctx,{flexDirection:"row",alignItems:"stretch",...sanitizedRootBoxOptions,...sanitizedRootOptions});if(this.internalId=ScrollBoxRenderable.idCounter++,this._stickyScroll=stickyScroll,this._stickyStart=stickyStart,this.scrollAccel=scrollAcceleration??new LinearScrollAccel,this.wrapper=new BoxRenderable(ctx,{flexDirection:"column",flexGrow:1,...wrapperOptions,id:`scroll-box-wrapper-${this.internalId}`}),super.add(this.wrapper),this.viewport=new BoxRenderable(ctx,{flexDirection:"column",flexGrow:1,overflow:"hidden",onSizeChange:()=>{this.recalculateBarProps()},...viewportOptions,id:`scroll-box-viewport-${this.internalId}`}),this.wrapper.add(this.viewport),this.content=new ContentRenderable(ctx,this.viewport,viewportCulling,{alignSelf:"flex-start",flexShrink:0,...scrollX?{minWidth:"100%"}:{minWidth:"100%",maxWidth:"100%"},...scrollY?{minHeight:"100%"}:{minHeight:"100%",maxHeight:"100%"},onSizeChange:()=>{this.recalculateBarProps()},...mergedContentOptions,id:`scroll-box-content-${this.internalId}`}),this.viewport.add(this.content),this.verticalScrollBar=new ScrollBarRenderable(ctx,{...scrollbarOptions,...verticalScrollbarOptions,arrowOptions:{...scrollbarOptions?.arrowOptions,...verticalScrollbarOptions?.arrowOptions},id:`scroll-box-vertical-scrollbar-${this.internalId}`,orientation:"vertical",onChange:(position)=>{if(this.content.translateY=-position,!this._isApplyingStickyScroll){let maxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height);if(!this.isAtStickyPosition()&&maxScrollTop>1)this._hasManualScroll=!0}this.updateStickyState()}}),super.add(this.verticalScrollBar),this.horizontalScrollBar=new ScrollBarRenderable(ctx,{...scrollbarOptions,...horizontalScrollbarOptions,arrowOptions:{...scrollbarOptions?.arrowOptions,...horizontalScrollbarOptions?.arrowOptions},id:`scroll-box-horizontal-scrollbar-${this.internalId}`,orientation:"horizontal",onChange:(position)=>{if(this.content.translateX=-position,!this._isApplyingStickyScroll){let maxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);if(!this.isAtStickyPosition()&&maxScrollLeft>1)this._hasManualScroll=!0}this.updateStickyState()}}),this.wrapper.add(this.horizontalScrollBar),this.recalculateBarProps(),stickyStart&&stickyScroll)this.applyStickyStart(stickyStart);this.selectionListener=()=>{let selection=this._ctx.getSelection();if(!selection||!selection.isDragging)this.stopAutoScroll()},this._ctx.on("selection",this.selectionListener)}onUpdate(deltaTime){this.handleAutoScroll(deltaTime)}scrollBy(delta,unit="absolute"){if(typeof delta==="number")this.verticalScrollBar.scrollBy(delta,unit);else this.verticalScrollBar.scrollBy(delta.y,unit),this.horizontalScrollBar.scrollBy(delta.x,unit)}scrollChildIntoView(childId){let child=this.content.findDescendantById(childId);if(!child)return;let getNearestDelta=(elementStart,elementEnd,viewportStart,viewportEnd)=>{let elementSize=elementEnd-elementStart,viewportSize=viewportEnd-viewportStart,elementStartOutside=elementStart<viewportStart,elementEndOutside=elementEnd>viewportEnd;if(elementStartOutside&&elementEndOutside)return 0;if(elementStartOutside&&elementSize<viewportSize||elementEndOutside&&elementSize>viewportSize)return elementStart-viewportStart;if(elementStartOutside&&elementSize>viewportSize||elementEndOutside&&elementSize<viewportSize)return elementEnd-viewportEnd;return 0},childTop=child.y,childBottom=child.y+child.height,viewportTop=this.viewport.y,viewportBottom=this.viewport.y+this.viewport.height,dy=getNearestDelta(childTop,childBottom,viewportTop,viewportBottom),childLeft=child.x,childRight=child.x+child.width,viewportLeft=this.viewport.x,viewportRight=this.viewport.x+this.viewport.width,dx=getNearestDelta(childLeft,childRight,viewportLeft,viewportRight);if(dx!==0||dy!==0)this.scrollBy({x:dx,y:dy})}scrollTo(position){if(typeof position==="number")this.scrollTop=position;else this.scrollTop=position.y,this.scrollLeft=position.x}isAtStickyPosition(){if(!this._stickyScroll||!this._stickyStart)return!1;let maxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height),maxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);switch(this._stickyStart){case"top":return this.scrollTop===0;case"bottom":return this.scrollTop>=maxScrollTop;case"left":return this.scrollLeft===0;case"right":return this.scrollLeft>=maxScrollLeft;default:return!1}}add(obj,index){return this.content.add(obj,index)}insertBefore(obj,anchor){return this.content.insertBefore(obj,anchor)}remove(id){this.content.remove(id)}getChildren(){return this.content.getChildren()}onMouseEvent(event){if(event.type==="scroll"){let dir=event.scroll?.direction;if(event.modifiers.shift)dir=dir==="up"?"left":dir==="down"?"right":dir==="right"?"down":"up";let baseDelta=event.scroll?.delta??0,now=Date.now(),multiplier=this.scrollAccel.tick(now),scrollAmount=baseDelta*multiplier;if(dir==="up"){this.scrollAccumulatorY-=scrollAmount;let integerScroll=Math.trunc(this.scrollAccumulatorY);if(integerScroll!==0)this.scrollTop+=integerScroll,this.scrollAccumulatorY-=integerScroll}else if(dir==="down"){this.scrollAccumulatorY+=scrollAmount;let integerScroll=Math.trunc(this.scrollAccumulatorY);if(integerScroll!==0)this.scrollTop+=integerScroll,this.scrollAccumulatorY-=integerScroll}else if(dir==="left"){this.scrollAccumulatorX-=scrollAmount;let integerScroll=Math.trunc(this.scrollAccumulatorX);if(integerScroll!==0)this.scrollLeft+=integerScroll,this.scrollAccumulatorX-=integerScroll}else if(dir==="right"){this.scrollAccumulatorX+=scrollAmount;let integerScroll=Math.trunc(this.scrollAccumulatorX);if(integerScroll!==0)this.scrollLeft+=integerScroll,this.scrollAccumulatorX-=integerScroll}let maxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height),maxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);if(maxScrollTop>1||maxScrollLeft>1)this._hasManualScroll=!0}if(event.type==="drag"&&event.isDragging)this.updateAutoScroll(event.x,event.y);else if(event.type==="up")this.stopAutoScroll()}handleKeyPress(key){if(this.verticalScrollBar.handleKeyPress(key))return this._hasManualScroll=!0,this.scrollAccel.reset(),this.resetScrollAccumulators(),!0;if(this.horizontalScrollBar.handleKeyPress(key))return this._hasManualScroll=!0,this.scrollAccel.reset(),this.resetScrollAccumulators(),!0;return!1}resetScrollAccumulators(){this.scrollAccumulatorX=0,this.scrollAccumulatorY=0}startAutoScroll(mouseX,mouseY){if(this.stopAutoScroll(),this.autoScrollMouseX=mouseX,this.autoScrollMouseY=mouseY,this.cachedAutoScrollSpeed=this.getAutoScrollSpeed(mouseX,mouseY),this.isAutoScrolling=!0,!this.live)this.live=!0}updateAutoScroll(mouseX,mouseY){this.autoScrollMouseX=mouseX,this.autoScrollMouseY=mouseY,this.cachedAutoScrollSpeed=this.getAutoScrollSpeed(mouseX,mouseY);let scrollX=this.getAutoScrollDirectionX(mouseX),scrollY=this.getAutoScrollDirectionY(mouseY);if(scrollX===0&&scrollY===0)this.stopAutoScroll();else if(!this.isAutoScrolling)this.startAutoScroll(mouseX,mouseY)}stopAutoScroll(){let wasAutoScrolling=this.isAutoScrolling;if(this.isAutoScrolling=!1,this.autoScrollAccumulatorX=0,this.autoScrollAccumulatorY=0,wasAutoScrolling&&!this.hasOtherLiveReasons())this.live=!1}hasOtherLiveReasons(){return!1}handleAutoScroll(deltaTime){if(!this.isAutoScrolling)return;let scrollX=this.getAutoScrollDirectionX(this.autoScrollMouseX),scrollY=this.getAutoScrollDirectionY(this.autoScrollMouseY),scrollAmount=this.cachedAutoScrollSpeed*(deltaTime/1000),scrolled=!1;if(scrollX!==0){this.autoScrollAccumulatorX+=scrollX*scrollAmount;let integerScrollX=Math.trunc(this.autoScrollAccumulatorX);if(integerScrollX!==0)this.scrollLeft+=integerScrollX,this.autoScrollAccumulatorX-=integerScrollX,scrolled=!0}if(scrollY!==0){this.autoScrollAccumulatorY+=scrollY*scrollAmount;let integerScrollY=Math.trunc(this.autoScrollAccumulatorY);if(integerScrollY!==0)this.scrollTop+=integerScrollY,this.autoScrollAccumulatorY-=integerScrollY,scrolled=!0}if(scrolled)this._ctx.requestSelectionUpdate();if(scrollX===0&&scrollY===0)this.stopAutoScroll()}getAutoScrollDirectionX(mouseX){let relativeX=mouseX-this.x,distToLeft=relativeX,distToRight=this.width-relativeX;if(distToLeft<=this.autoScrollThresholdHorizontal)return this.scrollLeft>0?-1:0;else if(distToRight<=this.autoScrollThresholdHorizontal){let maxScrollLeft=this.scrollWidth-this.viewport.width;return this.scrollLeft<maxScrollLeft?1:0}return 0}getAutoScrollDirectionY(mouseY){let relativeY=mouseY-this.y,distToTop=relativeY,distToBottom=this.height-relativeY;if(distToTop<=this.autoScrollThresholdVertical)return this.scrollTop>0?-1:0;else if(distToBottom<=this.autoScrollThresholdVertical){let maxScrollTop=this.scrollHeight-this.viewport.height;return this.scrollTop<maxScrollTop?1:0}return 0}getAutoScrollSpeed(mouseX,mouseY){let relativeX=mouseX-this.x,relativeY=mouseY-this.y,distToLeft=relativeX,distToRight=this.width-relativeX,distToTop=relativeY,distToBottom=this.height-relativeY,minDistance=Math.min(distToLeft,distToRight,distToTop,distToBottom);if(minDistance<=1)return this.autoScrollSpeedFast;else if(minDistance<=2)return this.autoScrollSpeedMedium;else return this.autoScrollSpeedSlow}recalculateBarProps(){let wasApplyingStickyScroll=this._isApplyingStickyScroll;this._isApplyingStickyScroll=!0;try{if(this.verticalScrollBar.scrollSize=this.content.height,this.verticalScrollBar.viewportSize=this.viewport.height,this.horizontalScrollBar.scrollSize=this.content.width,this.horizontalScrollBar.viewportSize=this.viewport.width,this._stickyScroll){let newMaxScrollTop=Math.max(0,this.scrollHeight-this.viewport.height),newMaxScrollLeft=Math.max(0,this.scrollWidth-this.viewport.width);if(this._stickyStart&&!this._hasManualScroll)this.applyStickyStart(this._stickyStart);else{if(this._stickyScrollTop)this.scrollTop=0;else if(this._stickyScrollBottom&&newMaxScrollTop>0)this.scrollTop=newMaxScrollTop;if(this._stickyScrollLeft)this.scrollLeft=0;else if(this._stickyScrollRight&&newMaxScrollLeft>0)this.scrollLeft=newMaxScrollLeft}}}finally{this._isApplyingStickyScroll=wasApplyingStickyScroll}process.nextTick(()=>{this.requestRender()})}set padding(value){this.content.padding=value,this.requestRender()}set paddingX(value){this.content.paddingX=value,this.requestRender()}set paddingY(value){this.content.paddingY=value,this.requestRender()}set paddingTop(value){this.content.paddingTop=value,this.requestRender()}set paddingRight(value){this.content.paddingRight=value,this.requestRender()}set paddingBottom(value){this.content.paddingBottom=value,this.requestRender()}set paddingLeft(value){this.content.paddingLeft=value,this.requestRender()}set rootOptions(options){Object.assign(this,options),this.requestRender()}set wrapperOptions(options){Object.assign(this.wrapper,options),this.requestRender()}set viewportOptions(options){Object.assign(this.viewport,options),this.requestRender()}set contentOptions(options){Object.assign(this.content,options),this.requestRender()}set scrollbarOptions(options){Object.assign(this.verticalScrollBar,options),Object.assign(this.horizontalScrollBar,options),this.requestRender()}set verticalScrollbarOptions(options){Object.assign(this.verticalScrollBar,options),this.requestRender()}set horizontalScrollbarOptions(options){Object.assign(this.horizontalScrollBar,options),this.requestRender()}get scrollAcceleration(){return this.scrollAccel}set scrollAcceleration(value){this.scrollAccel=value}get viewportCulling(){return this.content.viewportCulling}set viewportCulling(value){this.content.viewportCulling=value,this.requestRender()}destroySelf(){if(this.selectionListener)this._ctx.off("selection",this.selectionListener),this.selectionListener=void 0;super.destroySelf()}}var defaultSelectKeybindings=[{name:"up",action:"move-up"},{name:"k",action:"move-up"},{name:"down",action:"move-down"},{name:"j",action:"move-down"},{name:"up",shift:!0,action:"move-up-fast"},{name:"down",shift:!0,action:"move-down-fast"},{name:"return",action:"select-current"},{name:"linefeed",action:"select-current"}],SelectRenderableEvents;((SelectRenderableEvents2)=>{SelectRenderableEvents2.SELECTION_CHANGED="selectionChanged",SelectRenderableEvents2.ITEM_SELECTED="itemSelected"})(SelectRenderableEvents||={});class SelectRenderable extends Renderable{_focusable=!0;_options=[];_selectedIndex=0;scrollOffset=0;maxVisibleItems;_backgroundColor;_textColor;_focusedBackgroundColor;_focusedTextColor;_selectedBackgroundColor;_selectedTextColor;_descriptionColor;_selectedDescriptionColor;_showScrollIndicator;_wrapSelection;_showDescription;_font;_itemSpacing;linesPerItem;fontHeight;_fastScrollStep;_keyBindingsMap;_keyAliasMap;_keyBindings;_defaultOptions={backgroundColor:"transparent",textColor:"#FFFFFF",focusedBackgroundColor:"#1a1a1a",focusedTextColor:"#FFFFFF",selectedBackgroundColor:"#334455",selectedTextColor:"#FFFF00",selectedIndex:0,descriptionColor:"#888888",selectedDescriptionColor:"#CCCCCC",showScrollIndicator:!1,wrapSelection:!1,showDescription:!0,itemSpacing:0,fastScrollStep:5};constructor(ctx,options){super(ctx,{...options,buffered:!0});this._options=options.options||[];let requestedIndex=options.selectedIndex??this._defaultOptions.selectedIndex;this._selectedIndex=this._options.length>0?Math.min(requestedIndex,this._options.length-1):0,this._backgroundColor=parseColor(options.backgroundColor||this._defaultOptions.backgroundColor),this._textColor=parseColor(options.textColor||this._defaultOptions.textColor),this._focusedBackgroundColor=parseColor(options.focusedBackgroundColor||this._defaultOptions.focusedBackgroundColor),this._focusedTextColor=parseColor(options.focusedTextColor||this._defaultOptions.focusedTextColor),this._showScrollIndicator=options.showScrollIndicator??this._defaultOptions.showScrollIndicator,this._wrapSelection=options.wrapSelection??this._defaultOptions.wrapSelection,this._showDescription=options.showDescription??this._defaultOptions.showDescription,this._font=options.font,this._itemSpacing=options.itemSpacing||this._defaultOptions.itemSpacing,this.fontHeight=this._font?measureText({text:"A",font:this._font}).height:1,this.linesPerItem=this._showDescription?this._font?this.fontHeight+1:2:this._font?this.fontHeight:1,this.linesPerItem+=this._itemSpacing,this.maxVisibleItems=Math.max(1,Math.floor(this.height/this.linesPerItem)),this._selectedBackgroundColor=parseColor(options.selectedBackgroundColor||this._defaultOptions.selectedBackgroundColor),this._selectedTextColor=parseColor(options.selectedTextColor||this._defaultOptions.selectedTextColor),this._descriptionColor=parseColor(options.descriptionColor||this._defaultOptions.descriptionColor),this._selectedDescriptionColor=parseColor(options.selectedDescriptionColor||this._defaultOptions.selectedDescriptionColor),this._fastScrollStep=options.fastScrollStep||this._defaultOptions.fastScrollStep,this._keyAliasMap=mergeKeyAliases(defaultKeyAliases,options.keyAliasMap||{}),this._keyBindings=options.keyBindings||[];let mergedBindings=mergeKeyBindings(defaultSelectKeybindings,this._keyBindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap),this.requestRender()}renderSelf(buffer,deltaTime){if(!this.visible||!this.frameBuffer)return;if(this.isDirty)this.refreshFrameBuffer()}refreshFrameBuffer(){if(!this.frameBuffer)return;let bgColor=this._focused?this._focusedBackgroundColor:this._backgroundColor;if(this.frameBuffer.clear(bgColor),this._options.length===0)return;let contentX=0,contentY=0,contentWidth=this.width,contentHeight=this.height,visibleOptions=this._options.slice(this.scrollOffset,this.scrollOffset+this.maxVisibleItems);for(let i=0;i<visibleOptions.length;i++){let actualIndex=this.scrollOffset+i,option=visibleOptions[i],isSelected=actualIndex===this._selectedIndex,itemY=contentY+i*this.linesPerItem;if(itemY+this.linesPerItem-1>=contentY+contentHeight)break;if(isSelected){let contentHeight2=this.linesPerItem-this._itemSpacing;this.frameBuffer.fillRect(contentX,itemY,contentWidth,contentHeight2,this._selectedBackgroundColor)}let nameContent=`${isSelected?"\u25B6 ":" "}${option.name}`,baseTextColor=this._focused?this._focusedTextColor:this._textColor,nameColor=isSelected?this._selectedTextColor:baseTextColor,descX=contentX+3;if(this._font){let indicator=isSelected?"\u25B6 ":" ";this.frameBuffer.drawText(indicator,contentX+1,itemY,nameColor);let indicatorWidth=2;renderFontToFrameBuffer(this.frameBuffer,{text:option.name,x:contentX+1+indicatorWidth,y:itemY,color:nameColor,backgroundColor:isSelected?this._selectedBackgroundColor:bgColor,font:this._font}),descX=contentX+1+indicatorWidth}else this.frameBuffer.drawText(nameContent,contentX+1,itemY,nameColor);if(this._showDescription&&itemY+this.fontHeight<contentY+contentHeight){let descColor=isSelected?this._selectedDescriptionColor:this._descriptionColor;this.frameBuffer.drawText(option.description,descX,itemY+this.fontHeight,descColor)}}if(this._showScrollIndicator&&this._options.length>this.maxVisibleItems)this.renderScrollIndicatorToFrameBuffer(contentX,contentY,contentWidth,contentHeight)}renderScrollIndicatorToFrameBuffer(contentX,contentY,contentWidth,contentHeight){if(!this.frameBuffer)return;let scrollPercent=this._selectedIndex/Math.max(1,this._options.length-1),indicatorHeight=Math.max(1,contentHeight-2),indicatorY=contentY+1+Math.floor(scrollPercent*indicatorHeight),indicatorX=contentX+contentWidth-1;this.frameBuffer.drawText("\u2588",indicatorX,indicatorY,parseColor("#666666"))}get options(){return this._options}set options(options){this._options=options,this._selectedIndex=Math.min(this._selectedIndex,Math.max(0,options.length-1)),this.updateScrollOffset(),this.requestRender()}getSelectedOption(){return this._options[this._selectedIndex]||null}getSelectedIndex(){return this._selectedIndex}moveUp(steps=1){let newIndex=this._selectedIndex-steps;if(newIndex>=0)this._selectedIndex=newIndex;else if(this._wrapSelection&&this._options.length>0)this._selectedIndex=this._options.length-1;else this._selectedIndex=0;this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this._selectedIndex,this.getSelectedOption())}moveDown(steps=1){let newIndex=this._selectedIndex+steps;if(newIndex<this._options.length)this._selectedIndex=newIndex;else if(this._wrapSelection&&this._options.length>0)this._selectedIndex=0;else this._selectedIndex=this._options.length-1;this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this._selectedIndex,this.getSelectedOption())}selectCurrent(){let selected=this.getSelectedOption();if(selected)this.emit("itemSelected",this._selectedIndex,selected)}setSelectedIndex(index){if(index>=0&&index<this._options.length)this._selectedIndex=index,this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this._selectedIndex,this.getSelectedOption())}updateScrollOffset(){if(!this._options)return;let halfVisible=Math.floor(this.maxVisibleItems/2),newScrollOffset=Math.max(0,Math.min(this._selectedIndex-halfVisible,this._options.length-this.maxVisibleItems));if(newScrollOffset!==this.scrollOffset)this.scrollOffset=newScrollOffset,this.requestRender()}onResize(width,height){this.maxVisibleItems=Math.max(1,Math.floor(height/this.linesPerItem)),this.updateScrollOffset(),this.requestRender()}handleKeyPress(key){let action=getKeyBindingAction(this._keyBindingsMap,key);if(action)switch(action){case"move-up":return this.moveUp(1),!0;case"move-down":return this.moveDown(1),!0;case"move-up-fast":return this.moveUp(this._fastScrollStep),!0;case"move-down-fast":return this.moveDown(this._fastScrollStep),!0;case"select-current":return this.selectCurrent(),!0}return!1}get showScrollIndicator(){return this._showScrollIndicator}set showScrollIndicator(show){this._showScrollIndicator=show,this.requestRender()}get showDescription(){return this._showDescription}set showDescription(show){if(this._showDescription!==show)this._showDescription=show,this.linesPerItem=this._showDescription?this._font?this.fontHeight+1:2:this._font?this.fontHeight:1,this.linesPerItem+=this._itemSpacing,this.maxVisibleItems=Math.max(1,Math.floor(this.height/this.linesPerItem)),this.updateScrollOffset(),this.requestRender()}get wrapSelection(){return this._wrapSelection}set wrapSelection(wrap){this._wrapSelection=wrap}set backgroundColor(value){let newColor=parseColor(value??this._defaultOptions.backgroundColor);if(this._backgroundColor!==newColor)this._backgroundColor=newColor,this.requestRender()}set textColor(value){let newColor=parseColor(value??this._defaultOptions.textColor);if(this._textColor!==newColor)this._textColor=newColor,this.requestRender()}set focusedBackgroundColor(value){let newColor=parseColor(value??this._defaultOptions.focusedBackgroundColor);if(this._focusedBackgroundColor!==newColor)this._focusedBackgroundColor=newColor,this.requestRender()}set focusedTextColor(value){let newColor=parseColor(value??this._defaultOptions.focusedTextColor);if(this._focusedTextColor!==newColor)this._focusedTextColor=newColor,this.requestRender()}set selectedBackgroundColor(value){let newColor=parseColor(value??this._defaultOptions.selectedBackgroundColor);if(this._selectedBackgroundColor!==newColor)this._selectedBackgroundColor=newColor,this.requestRender()}set selectedTextColor(value){let newColor=parseColor(value??this._defaultOptions.selectedTextColor);if(this._selectedTextColor!==newColor)this._selectedTextColor=newColor,this.requestRender()}set descriptionColor(value){let newColor=parseColor(value??this._defaultOptions.descriptionColor);if(this._descriptionColor!==newColor)this._descriptionColor=newColor,this.requestRender()}set selectedDescriptionColor(value){let newColor=parseColor(value??this._defaultOptions.selectedDescriptionColor);if(this._selectedDescriptionColor!==newColor)this._selectedDescriptionColor=newColor,this.requestRender()}set font(font){this._font=font,this.fontHeight=measureText({text:"A",font:this._font}).height,this.linesPerItem=this._showDescription?this._font?this.fontHeight+1:2:this._font?this.fontHeight:1,this.linesPerItem+=this._itemSpacing,this.maxVisibleItems=Math.max(1,Math.floor(this.height/this.linesPerItem)),this.updateScrollOffset(),this.requestRender()}set itemSpacing(spacing){this._itemSpacing=spacing,this.linesPerItem=this._showDescription?this._font?this.fontHeight+1:2:this._font?this.fontHeight:1,this.linesPerItem+=this._itemSpacing,this.maxVisibleItems=Math.max(1,Math.floor(this.height/this.linesPerItem)),this.updateScrollOffset(),this.requestRender()}set fastScrollStep(step){this._fastScrollStep=step}set keyBindings(bindings){this._keyBindings=bindings;let mergedBindings=mergeKeyBindings(defaultSelectKeybindings,bindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap)}set keyAliasMap(aliases){this._keyAliasMap=mergeKeyAliases(defaultKeyAliases,aliases);let mergedBindings=mergeKeyBindings(defaultSelectKeybindings,this._keyBindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap)}set selectedIndex(value){let newIndex=value??this._defaultOptions.selectedIndex,clampedIndex=this._options.length>0?Math.min(Math.max(0,newIndex),this._options.length-1):0;if(this._selectedIndex!==clampedIndex)this._selectedIndex=clampedIndex,this.updateScrollOffset(),this.requestRender()}}var defaultTabSelectKeybindings=[{name:"left",action:"move-left"},{name:"[",action:"move-left"},{name:"right",action:"move-right"},{name:"]",action:"move-right"},{name:"return",action:"select-current"},{name:"linefeed",action:"select-current"}],TabSelectRenderableEvents;((TabSelectRenderableEvents2)=>{TabSelectRenderableEvents2.SELECTION_CHANGED="selectionChanged",TabSelectRenderableEvents2.ITEM_SELECTED="itemSelected"})(TabSelectRenderableEvents||={});function calculateDynamicHeight(showUnderline,showDescription){let height=1;if(showUnderline)height+=1;if(showDescription)height+=1;return height}class TabSelectRenderable extends Renderable{_focusable=!0;_options=[];selectedIndex=0;scrollOffset=0;_tabWidth;maxVisibleTabs;_backgroundColor;_textColor;_focusedBackgroundColor;_focusedTextColor;_selectedBackgroundColor;_selectedTextColor;_selectedDescriptionColor;_showScrollArrows;_showDescription;_showUnderline;_wrapSelection;_keyBindingsMap;_keyAliasMap;_keyBindings;constructor(ctx,options){let calculatedHeight=calculateDynamicHeight(options.showUnderline??!0,options.showDescription??!0);super(ctx,{...options,height:calculatedHeight,buffered:!0});this._backgroundColor=parseColor(options.backgroundColor||"transparent"),this._textColor=parseColor(options.textColor||"#FFFFFF"),this._focusedBackgroundColor=parseColor(options.focusedBackgroundColor||options.backgroundColor||"#1a1a1a"),this._focusedTextColor=parseColor(options.focusedTextColor||options.textColor||"#FFFFFF"),this._options=options.options||[],this._tabWidth=options.tabWidth||20,this._showDescription=options.showDescription??!0,this._showUnderline=options.showUnderline??!0,this._showScrollArrows=options.showScrollArrows??!0,this._wrapSelection=options.wrapSelection??!1,this.maxVisibleTabs=Math.max(1,Math.floor(this.width/this._tabWidth)),this._selectedBackgroundColor=parseColor(options.selectedBackgroundColor||"#334455"),this._selectedTextColor=parseColor(options.selectedTextColor||"#FFFF00"),this._selectedDescriptionColor=parseColor(options.selectedDescriptionColor||"#CCCCCC"),this._keyAliasMap=mergeKeyAliases(defaultKeyAliases,options.keyAliasMap||{}),this._keyBindings=options.keyBindings||[];let mergedBindings=mergeKeyBindings(defaultTabSelectKeybindings,this._keyBindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap)}calculateDynamicHeight(){return calculateDynamicHeight(this._showUnderline,this._showDescription)}renderSelf(buffer,deltaTime){if(!this.visible||!this.frameBuffer)return;if(this.isDirty)this.refreshFrameBuffer()}refreshFrameBuffer(){if(!this.frameBuffer)return;let bgColor=this._focused?this._focusedBackgroundColor:this._backgroundColor;if(this.frameBuffer.clear(bgColor),this._options.length===0)return;let contentX=0,contentY=0,contentWidth=this.width,contentHeight=this.height,visibleOptions=this._options.slice(this.scrollOffset,this.scrollOffset+this.maxVisibleTabs);for(let i=0;i<visibleOptions.length;i++){let actualIndex=this.scrollOffset+i,option=visibleOptions[i],isSelected=actualIndex===this.selectedIndex,tabX=contentX+i*this._tabWidth;if(tabX>=contentX+contentWidth)break;let actualTabWidth=Math.min(this._tabWidth,contentWidth-i*this._tabWidth);if(isSelected)this.frameBuffer.fillRect(tabX,contentY,actualTabWidth,1,this._selectedBackgroundColor);let baseTextColor=this._focused?this._focusedTextColor:this._textColor,nameColor=isSelected?this._selectedTextColor:baseTextColor,nameContent=this.truncateText(option.name,actualTabWidth-2);if(this.frameBuffer.drawText(nameContent,tabX+1,contentY,nameColor),isSelected&&this._showUnderline&&contentHeight>=2){let underlineY=contentY+1,underlineBg=isSelected?this._selectedBackgroundColor:bgColor;this.frameBuffer.drawText("\u25AC".repeat(actualTabWidth),tabX,underlineY,nameColor,underlineBg)}}if(this._showDescription&&contentHeight>=(this._showUnderline?3:2)){let selectedOption=this.getSelectedOption();if(selectedOption){let descriptionY=contentY+(this._showUnderline?2:1),descColor=this._selectedDescriptionColor,descContent=this.truncateText(selectedOption.description,contentWidth-2);this.frameBuffer.drawText(descContent,contentX+1,descriptionY,descColor)}}if(this._showScrollArrows&&this._options.length>this.maxVisibleTabs)this.renderScrollArrowsToFrameBuffer(contentX,contentY,contentWidth,contentHeight)}truncateText(text,maxWidth){if(text.length<=maxWidth)return text;return text.substring(0,Math.max(0,maxWidth-1))+"\u2026"}renderScrollArrowsToFrameBuffer(contentX,contentY,contentWidth,contentHeight){if(!this.frameBuffer)return;let hasMoreLeft=this.scrollOffset>0,hasMoreRight=this.scrollOffset+this.maxVisibleTabs<this._options.length;if(hasMoreLeft)this.frameBuffer.drawText("\u2039",contentX,contentY,parseColor("#AAAAAA"));if(hasMoreRight)this.frameBuffer.drawText("\u203A",contentX+contentWidth-1,contentY,parseColor("#AAAAAA"))}setOptions(options){this._options=options,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,options.length-1)),this.updateScrollOffset(),this.requestRender()}getSelectedOption(){return this._options[this.selectedIndex]||null}getSelectedIndex(){return this.selectedIndex}moveLeft(){if(this.selectedIndex>0)this.selectedIndex--;else if(this._wrapSelection&&this._options.length>0)this.selectedIndex=this._options.length-1;else return;this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this.selectedIndex,this.getSelectedOption())}moveRight(){if(this.selectedIndex<this._options.length-1)this.selectedIndex++;else if(this._wrapSelection&&this._options.length>0)this.selectedIndex=0;else return;this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this.selectedIndex,this.getSelectedOption())}selectCurrent(){let selected=this.getSelectedOption();if(selected)this.emit("itemSelected",this.selectedIndex,selected)}setSelectedIndex(index){if(index>=0&&index<this._options.length)this.selectedIndex=index,this.updateScrollOffset(),this.requestRender(),this.emit("selectionChanged",this.selectedIndex,this.getSelectedOption())}updateScrollOffset(){let halfVisible=Math.floor(this.maxVisibleTabs/2),newScrollOffset=Math.max(0,Math.min(this.selectedIndex-halfVisible,this._options.length-this.maxVisibleTabs));if(newScrollOffset!==this.scrollOffset)this.scrollOffset=newScrollOffset,this.requestRender()}onResize(width,height){this.maxVisibleTabs=Math.max(1,Math.floor(width/this._tabWidth)),this.updateScrollOffset(),this.requestRender()}setTabWidth(tabWidth){if(this._tabWidth===tabWidth)return;this._tabWidth=tabWidth,this.maxVisibleTabs=Math.max(1,Math.floor(this.width/this._tabWidth)),this.updateScrollOffset(),this.requestRender()}getTabWidth(){return this._tabWidth}handleKeyPress(key){let action=getKeyBindingAction(this._keyBindingsMap,key);if(action)switch(action){case"move-left":return this.moveLeft(),!0;case"move-right":return this.moveRight(),!0;case"select-current":return this.selectCurrent(),!0}return!1}get options(){return this._options}set options(options){this._options=options,this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,options.length-1)),this.updateScrollOffset(),this.requestRender()}set backgroundColor(color){this._backgroundColor=parseColor(color),this.requestRender()}set textColor(color){this._textColor=parseColor(color),this.requestRender()}set focusedBackgroundColor(color){this._focusedBackgroundColor=parseColor(color),this.requestRender()}set focusedTextColor(color){this._focusedTextColor=parseColor(color),this.requestRender()}set selectedBackgroundColor(color){this._selectedBackgroundColor=parseColor(color),this.requestRender()}set selectedTextColor(color){this._selectedTextColor=parseColor(color),this.requestRender()}set selectedDescriptionColor(color){this._selectedDescriptionColor=parseColor(color),this.requestRender()}get showDescription(){return this._showDescription}set showDescription(show){if(this._showDescription!==show){this._showDescription=show;let newHeight=this.calculateDynamicHeight();this.height=newHeight,this.requestRender()}}get showUnderline(){return this._showUnderline}set showUnderline(show){if(this._showUnderline!==show){this._showUnderline=show;let newHeight=this.calculateDynamicHeight();this.height=newHeight,this.requestRender()}}get showScrollArrows(){return this._showScrollArrows}set showScrollArrows(show){if(this._showScrollArrows!==show)this._showScrollArrows=show,this.requestRender()}get wrapSelection(){return this._wrapSelection}set wrapSelection(wrap){this._wrapSelection=wrap}get tabWidth(){return this._tabWidth}set tabWidth(tabWidth){if(this._tabWidth===tabWidth)return;this._tabWidth=tabWidth,this.maxVisibleTabs=Math.max(1,Math.floor(this.width/this._tabWidth)),this.updateScrollOffset(),this.requestRender()}set keyBindings(bindings){this._keyBindings=bindings;let mergedBindings=mergeKeyBindings(defaultTabSelectKeybindings,bindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap)}set keyAliasMap(aliases){this._keyAliasMap=mergeKeyAliases(defaultKeyAliases,aliases);let mergedBindings=mergeKeyBindings(defaultTabSelectKeybindings,this._keyBindings);this._keyBindingsMap=buildKeyBindingsMap(mergedBindings,this._keyAliasMap)}}class TimeToFirstDrawRenderable extends Renderable{_runtimeMs=null;textColor;label;precision;constructor(ctx,options={}){super(ctx,{width:"100%",height:1,flexShrink:0,alignSelf:"center",...options});this.textColor=parseColor(options.fg??"#AAAAAA"),this.label=options.label??"Time to first draw",this.precision=this.normalizePrecision(options.precision??2)}get runtimeMs(){return this._runtimeMs}set fg(value){this.textColor=parseColor(value),this.requestRender()}set color(value){this.fg=value}set textLabel(value){if(value===this.label)return;this.label=value,this.requestRender()}set decimals(value){let nextPrecision=this.normalizePrecision(value);if(nextPrecision===this.precision)return;this.precision=nextPrecision,this.requestRender()}reset(){this._runtimeMs=null,this.requestRender()}renderSelf(buffer){if(this._runtimeMs===null)this._runtimeMs=performance.now();let content=`${this.label}: ${this._runtimeMs.toFixed(this.precision)}ms`,maxWidth=Math.max(this.width,1),visibleContent=content.length>maxWidth?content.slice(0,maxWidth):content,centeredX=this.x+Math.max(0,Math.floor((maxWidth-visibleContent.length)/2));buffer.drawText(visibleContent,centeredX,this.y,this.textColor)}normalizePrecision(value){if(!Number.isFinite(value))return 2;return Math.max(0,Math.floor(value))}}var import_react=__toESM(require_react_production(),1);var import_react2=__toESM(require_react_production(),1),import_react3=__toESM(require_react_production(),1);var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");function jsxProd(type,config,maybeKey){var key=null;if(maybeKey!==void 0&&(key=""+maybeKey),config.key!==void 0&&(key=""+config.key),"key"in config){maybeKey={};for(var propName in config)propName!=="key"&&(maybeKey[propName]=config[propName])}else maybeKey=config;return config=maybeKey.ref,{$$typeof:REACT_ELEMENT_TYPE,type,key,ref:config!==void 0?config:null,props:maybeKey}}var $Fragment=REACT_FRAGMENT_TYPE,$jsx=jsxProd,$jsxs=jsxProd;var jsxDEV=$jsx;var import_react_reconciler=__toESM(require_react_reconciler_production(),1);var $ConcurrentRoot=1;var $DefaultEventPriority=32;var $NoEventPriority=0;var import_react4=__toESM(require_react_production(),1);var textNodeKeys=["span","b","strong","i","em","u","br","a"];class SpanRenderable extends TextNodeRenderable{ctx;constructor(ctx,options){super(options);this.ctx=ctx}}class TextModifierRenderable extends SpanRenderable{constructor(options,modifier){super(null,options);if(modifier==="b"||modifier==="strong")this.attributes=(this.attributes||0)|TextAttributes.BOLD;else if(modifier==="i"||modifier==="em")this.attributes=(this.attributes||0)|TextAttributes.ITALIC;else if(modifier==="u")this.attributes=(this.attributes||0)|TextAttributes.UNDERLINE}}class BoldSpanRenderable extends TextModifierRenderable{constructor(_ctx,options){super(options,"b")}}class ItalicSpanRenderable extends TextModifierRenderable{constructor(_ctx,options){super(options,"i")}}class UnderlineSpanRenderable extends TextModifierRenderable{constructor(_ctx,options){super(options,"u")}}class LineBreakRenderable extends SpanRenderable{constructor(_ctx,options){super(null,options);this.add()}add(){return super.add(`
|
|
3666
3666
|
`)}}class LinkRenderable extends SpanRenderable{constructor(_ctx,options){let linkOptions={...options,link:{url:options.href}};super(null,linkOptions)}}var baseComponents={box:BoxRenderable,text:TextRenderable,code:CodeRenderable,diff:DiffRenderable,markdown:MarkdownRenderable,input:InputRenderable,select:SelectRenderable,textarea:TextareaRenderable,scrollbox:ScrollBoxRenderable,"ascii-font":ASCIIFontRenderable,"tab-select":TabSelectRenderable,"line-number":LineNumberRenderable,span:SpanRenderable,br:LineBreakRenderable,b:BoldSpanRenderable,strong:BoldSpanRenderable,i:ItalicSpanRenderable,em:ItalicSpanRenderable,u:UnderlineSpanRenderable,a:LinkRenderable},componentCatalogue={...baseComponents};function extend(objects){Object.assign(componentCatalogue,objects)}function getComponentCatalogue(){return componentCatalogue}var AppContext=import_react.createContext({keyHandler:null,renderer:null}),useAppContext=()=>{return import_react.useContext(AppContext)};class ErrorBoundary extends import_react3.default.Component{constructor(props){super(props);this.state={hasError:!1,error:null}}static getDerivedStateFromError(error){return{hasError:!0,error}}render(){if(this.state.hasError&&this.state.error)return jsxDEV("box",{style:{flexDirection:"column",padding:2},children:jsxDEV("text",{fg:"red",children:this.state.error.stack||this.state.error.message},void 0,!1,void 0,this)},void 0,!1,void 0,this);return this.props.children}}var package_default={name:"@opentui/react",version:"0.2.2",description:"React renderer for building terminal user interfaces using OpenTUI core",license:"MIT",repository:{type:"git",url:"https://github.com/anomalyco/opentui",directory:"packages/react"},module:"src/index.ts",type:"module",private:!0,main:"src/index.ts",exports:{".":{import:"./src/index.ts",types:"./src/index.ts"},"./test-utils":{import:"./src/test-utils.ts",types:"./src/test-utils.d.ts"},"./runtime-plugin-support":{import:"./scripts/runtime-plugin-support.ts",types:"./scripts/runtime-plugin-support.ts"},"./runtime-plugin-support/configure":{import:"./scripts/runtime-plugin-support-configure.ts",types:"./scripts/runtime-plugin-support-configure.ts"},"./jsx-runtime":{import:"./jsx-runtime.js",types:"./jsx-runtime.d.ts"},"./jsx-dev-runtime":{import:"./jsx-dev-runtime.js",types:"./jsx-dev-runtime.d.ts"}},scripts:{build:"bun run scripts/build.ts","build:examples":"bun examples/build.ts","build:dev":"bun run scripts/build.ts --dev",publish:"bun run scripts/publish.ts",test:"bun test"},devDependencies:{"@opentui/keymap":"workspace:*","@types/bun":"latest","@types/node":"^24.0.0","@types/react":"^19.0.0","@types/react-reconciler":"^0.32.0","@types/ws":"^8.18.1",react:">=19.0.0","react-devtools-core":"^7.0.1",typescript:"^5",ws:"^8.18.0"},peerDependencies:{react:">=19.0.0","react-devtools-core":"^7.0.1",ws:"^8.18.0"},peerDependenciesMeta:{"react-devtools-core":{optional:!0},ws:{optional:!0}},dependencies:{"@opentui/core":"workspace:*","react-reconciler":"^0.32.0"}},idCounter=new Map;function getNextId(type){if(!idCounter.has(type))idCounter.set(type,0);let value=idCounter.get(type)+1;return idCounter.set(type,value),`${type}-${value}`}function initEventListeners(instance,eventName,listener,previousListener){if(previousListener)instance.off(eventName,previousListener);if(listener)instance.on(eventName,listener)}function setStyle(instance,styles,oldStyles){if(oldStyles!=null&&typeof oldStyles==="object"){for(let styleName in oldStyles)if(oldStyles.hasOwnProperty(styleName)){if(styles==null||!styles.hasOwnProperty(styleName))instance[styleName]=null}}if(styles!=null&&typeof styles==="object"){for(let styleName in styles)if(styles.hasOwnProperty(styleName)){let value=styles[styleName],oldValue=oldStyles?.[styleName];if(value!==oldValue)instance[styleName]=value}}}function setProperty(instance,type,propKey,propValue,oldPropValue){switch(propKey){case"onChange":if(instance instanceof InputRenderable)initEventListeners(instance,InputRenderableEvents.CHANGE,propValue,oldPropValue);else if(instance instanceof SelectRenderable)initEventListeners(instance,SelectRenderableEvents.SELECTION_CHANGED,propValue,oldPropValue);else if(instance instanceof TabSelectRenderable)initEventListeners(instance,TabSelectRenderableEvents.SELECTION_CHANGED,propValue,oldPropValue);break;case"onInput":if(instance instanceof InputRenderable)initEventListeners(instance,InputRenderableEvents.INPUT,propValue,oldPropValue);break;case"onSubmit":if(instance instanceof InputRenderable)initEventListeners(instance,InputRenderableEvents.ENTER,propValue,oldPropValue);else if(instance instanceof TextareaRenderable)instance.onSubmit=propValue;break;case"onSelect":if(instance instanceof SelectRenderable)initEventListeners(instance,SelectRenderableEvents.ITEM_SELECTED,propValue,oldPropValue);else if(instance instanceof TabSelectRenderable)initEventListeners(instance,TabSelectRenderableEvents.ITEM_SELECTED,propValue,oldPropValue);break;case"focused":if(isRenderable(instance))if(propValue)instance.focus();else instance.blur();break;case"style":setStyle(instance,propValue,oldPropValue);break;case"children":break;default:instance[propKey]=propValue}}function setInitialProperties(instance,type,props){for(let propKey in props){if(!props.hasOwnProperty(propKey))continue;let propValue=props[propKey];if(propValue==null)continue;setProperty(instance,type,propKey,propValue)}}function updateProperties(instance,type,oldProps,newProps){for(let propKey in oldProps){let oldProp=oldProps[propKey];if(oldProps.hasOwnProperty(propKey)&&oldProp!=null&&!newProps.hasOwnProperty(propKey))setProperty(instance,type,propKey,null,oldProp)}for(let propKey in newProps){let newProp=newProps[propKey],oldProp=oldProps[propKey];if(newProps.hasOwnProperty(propKey)&&newProp!==oldProp&&(newProp!=null||oldProp!=null))setProperty(instance,type,propKey,newProp,oldProp)}}var currentUpdatePriority=$NoEventPriority,hostConfig={supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance(type,props,rootContainerInstance,hostContext){if(textNodeKeys.includes(type)&&!hostContext.isInsideText)throw Error(`Component of type "${type}" must be created inside of a text node`);let id=getNextId(type),components=getComponentCatalogue();if(!components[type])throw Error(`Unknown component type: ${type}`);return new components[type](rootContainerInstance.ctx,{id,...props})},appendChild(parent,child){parent.add(child)},removeChild(parent,child){parent.remove(child.id)},insertBefore(parent,child,beforeChild){parent.insertBefore(child,beforeChild)},insertInContainerBefore(parent,child,beforeChild){parent.insertBefore(child,beforeChild)},removeChildFromContainer(parent,child){parent.remove(child.id)},prepareForCommit(containerInfo){return null},resetAfterCommit(containerInfo){containerInfo.requestRender()},getRootHostContext(rootContainerInstance){return{isInsideText:!1}},getChildHostContext(parentHostContext,type,rootContainerInstance){let isInsideText=["text",...textNodeKeys].includes(type);return{...parentHostContext,isInsideText}},shouldSetTextContent(type,props){return!1},createTextInstance(text,rootContainerInstance,hostContext){if(!hostContext.isInsideText)throw Error("Text must be created inside of a text node");return TextNodeRenderable.fromString(text)},scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,shouldAttemptEagerTransition(){return!1},finalizeInitialChildren(instance,type,props,rootContainerInstance,hostContext){return setInitialProperties(instance,type,props),!1},commitMount(instance,type,props,internalInstanceHandle){},commitUpdate(instance,type,oldProps,newProps,internalInstanceHandle){updateProperties(instance,type,oldProps,newProps),instance.requestRender()},commitTextUpdate(textInstance,oldText,newText){textInstance.children=[newText],textInstance.requestRender()},appendChildToContainer(container,child){container.add(child)},appendInitialChild(parent,child){parent.add(child)},hideInstance(instance){instance.visible=!1,instance.requestRender()},unhideInstance(instance,props){instance.visible=!0,instance.requestRender()},hideTextInstance(textInstance){textInstance.visible=!1,textInstance.requestRender()},unhideTextInstance(textInstance,text){textInstance.visible=!0,textInstance.requestRender()},clearContainer(container){container.getChildren().forEach((child)=>container.remove(child.id))},setCurrentUpdatePriority(newPriority){currentUpdatePriority=newPriority},getCurrentUpdatePriority:()=>currentUpdatePriority,resolveUpdatePriority(){if(currentUpdatePriority!==$NoEventPriority)return currentUpdatePriority;return $DefaultEventPriority},maySuspendCommit(){return!1},NotPendingTransition:null,HostTransitionContext:import_react4.createContext(null),resetFormInstance(){},requestPostPaintCallback(){},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},detachDeletedInstance(instance){if(!instance.parent)instance.destroyRecursively()},getPublicInstance(instance){return instance},preparePortalMount(containerInfo){},isPrimaryRenderer:!0,getInstanceFromNode(){return null},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},prepareScopeUpdate(){},getInstanceFromScope(){return null},rendererPackageName:"@opentui/react",rendererVersion:package_default.version},reconciler=import_react_reconciler.default(hostConfig);reconciler.injectIntoDevTools();function _render(element,root){let container=reconciler.createContainer(root,$ConcurrentRoot,null,!1,null,"",console.error,console.error,console.error,console.error,null);return reconciler.updateContainer(element,container,null,()=>{}),container}var _r=reconciler,flushSync=_r.flushSyncFromReconciler??_r.flushSync;function createRoot(renderer){let container=null,cleanup=()=>{if(container)reconciler.updateContainer(null,container,null,()=>{}),reconciler.flushSyncWork(),container=null};return renderer.once(CliRenderEvents.DESTROY,cleanup),{render:(node)=>{engine.attach(renderer),container=_render(import_react2.default.createElement(AppContext.Provider,{value:{keyHandler:renderer.keyInput,renderer}},import_react2.default.createElement(ErrorBoundary,null,node)),renderer.root)},unmount:cleanup}}var import_react5=__toESM(require_react_production(),1),import_react6=__toESM(require_react_production(),1),import_react7=__toESM(require_react_production(),1),import_react8=__toESM(require_react_production(),1);var import_react9=__toESM(require_react_production(),1);var import_react10=__toESM(require_react_production(),1);var import_react11=__toESM(require_react_production(),1),import_react12=__toESM(require_react_production(),1);function useEffectEvent(handler){let handlerRef=import_react6.useRef(handler);return import_react6.useLayoutEffect(()=>{handlerRef.current=handler}),import_react6.useCallback((...args)=>{let fn=handlerRef.current;return fn(...args)},[])}var useKeyboard=(handler,options={release:!1})=>{let{keyHandler}=useAppContext(),stableHandler=useEffectEvent(handler);import_react5.useEffect(()=>{if(keyHandler?.on("keypress",stableHandler),options?.release)keyHandler?.on("keyrelease",stableHandler);return()=>{if(keyHandler?.off("keypress",stableHandler),options?.release)keyHandler?.off("keyrelease",stableHandler)}},[keyHandler,options.release])},useRenderer=()=>{let{renderer}=useAppContext();if(!renderer)throw Error("Renderer not found.");return renderer},useOnResize=(callback)=>{let renderer=useRenderer(),stableCallback=useEffectEvent(callback);return import_react7.useEffect(()=>{return renderer.on("resize",stableCallback),()=>{renderer.off("resize",stableCallback)}},[renderer]),renderer},useTerminalDimensions=()=>{let renderer=useRenderer(),[dimensions,setDimensions]=import_react8.useState({width:renderer.width,height:renderer.height});return useOnResize((width,height)=>{setDimensions({width,height})}),dimensions};function createReactSlotRegistry(renderer,context,options={}){return createSlotRegistry(renderer,"react:slot-registry",context,options)}function renderPluginFailurePlaceholder(registry,pluginFailurePlaceholder,failure,pluginId,slot){if(!pluginFailurePlaceholder)return null;try{return pluginFailurePlaceholder(failure)}catch(error){return registry.reportPluginError({pluginId,slot,phase:"error_placeholder",source:"react",error}),null}}class PluginErrorBoundary extends import_react10.default.Component{constructor(props){super(props);this.state={failure:null}}componentDidCatch(error){let failure=this.props.registry.reportPluginError({pluginId:this.props.pluginId,slot:this.props.slotName,phase:"render",source:"react",error});this.setState({failure})}componentDidUpdate(previousProps){if(previousProps.resetToken!==this.props.resetToken&&this.state.failure)this.setState({failure:null})}render(){if(this.state.failure){let placeholder=renderPluginFailurePlaceholder(this.props.registry,this.props.pluginFailurePlaceholder,this.state.failure,this.props.pluginId,this.props.slotName);if(placeholder===null||placeholder===void 0||placeholder===!1)return this.props.fallbackOnFailure??null;return placeholder}return this.props.children}}function getSlotProps(props){let{children:_children,mode:_mode,name:_name,registry:_registry,pluginFailurePlaceholder:_pluginFailurePlaceholder,...slotProps}=props;return slotProps}function createSlot(registry,options={}){return function(props){return jsxDEV(Slot,{...props,registry,pluginFailurePlaceholder:options.pluginFailurePlaceholder},void 0,!1,void 0,this)}}function Slot(props){let[version,setVersion]=import_react10.useState(0),registry=props.registry,slotName=String(props.name),renderFailuresByPluginRef=import_react10.useRef(new Map),pendingRenderReportsRef=import_react10.useRef(new Map);import_react10.useEffect(()=>{return registry.subscribe(()=>{setVersion((current)=>current+1)})},[registry]),import_react10.useEffect(()=>{if(pendingRenderReportsRef.current.size===0)return;let pendingReports=[...pendingRenderReportsRef.current.values()];pendingRenderReportsRef.current.clear();for(let report of pendingReports){let failure=registry.reportPluginError({pluginId:report.pluginId,slot:report.slot,phase:"render",source:"react",error:report.error});renderFailuresByPluginRef.current.set(`${report.slot}:${report.pluginId}:render`,failure)}});let entries=import_react10.useMemo(()=>registry.resolveEntries(props.name),[registry,props.name,version]),slotProps=getSlotProps(props),renderEntry=(entry,fallbackOnFailure)=>{let key=`${slotName}:${entry.id}`,failureKey=`${slotName}:${entry.id}:render`;try{let rendered=entry.renderer(registry.context,slotProps);return renderFailuresByPluginRef.current.delete(failureKey),pendingRenderReportsRef.current.delete(failureKey),jsxDEV(PluginErrorBoundary,{registry,pluginFailurePlaceholder:props.pluginFailurePlaceholder,pluginId:entry.id,slotName,resetToken:version,fallbackOnFailure,children:rendered},key,!1,void 0,this)}catch(error){let normalizedError=error instanceof Error?error:typeof error==="string"?Error(error):Error(String(error)),lastFailure=renderFailuresByPluginRef.current.get(failureKey),isSameFailure=lastFailure&&lastFailure.error.message===normalizedError.message;if(!isSameFailure){let queued=pendingRenderReportsRef.current.get(failureKey);if(!queued||queued.error.message!==normalizedError.message)pendingRenderReportsRef.current.set(failureKey,{pluginId:entry.id,slot:slotName,error:normalizedError})}let failure=isSameFailure&&lastFailure?lastFailure:{pluginId:entry.id,slot:slotName,phase:"render",source:"react",error:normalizedError,timestamp:Date.now()};renderFailuresByPluginRef.current.set(failureKey,failure);let placeholder=renderPluginFailurePlaceholder(registry,props.pluginFailurePlaceholder,failure,entry.id,slotName);if(placeholder===null||placeholder===void 0||placeholder===!1)return fallbackOnFailure??null;return jsxDEV(import_react10.Fragment,{children:placeholder},key,!1,void 0,this)}};if(entries.length===0)return jsxDEV($Fragment,{children:props.children},void 0,!1,void 0,this);if(props.mode==="single_winner"){let winner=entries[0];if(!winner)return jsxDEV($Fragment,{children:props.children},void 0,!1,void 0,this);let rendered=renderEntry(winner,props.children);if(rendered===null||rendered===void 0||rendered===!1)return jsxDEV($Fragment,{children:props.children},void 0,!1,void 0,this);return jsxDEV($Fragment,{children:rendered},void 0,!1,void 0,this)}if(props.mode==="replace"){if(entries.length===1){let rendered=renderEntry(entries[0],props.children);if(rendered===null||rendered===void 0||rendered===!1)return jsxDEV($Fragment,{children:props.children},void 0,!1,void 0,this);return jsxDEV($Fragment,{children:rendered},void 0,!1,void 0,this)}let renderedEntries=entries.map((entry)=>renderEntry(entry));if(!renderedEntries.some((node)=>node!==null&&node!==void 0&&node!==!1))return jsxDEV($Fragment,{children:props.children},void 0,!1,void 0,this);return jsxDEV($Fragment,{children:renderedEntries},void 0,!1,void 0,this)}return jsxDEV($Fragment,{children:[props.children,entries.map((entry)=>renderEntry(entry))]},void 0,!0,void 0,this)}extend({"time-to-first-draw":TimeToFirstDrawRenderable});init_perf();var import_react152=__toESM(require_react_production(),1);var INTERP_RE=/\{!(.+?)\}/g,hasInterp=(s)=>/\{!.+?\}/.test(s);async function interpolate(gw,text){let hits=[...text.matchAll(INTERP_RE)];if(hits.length===0)return text;let outs=await Promise.all(hits.map((m2)=>gw.request("shell.exec",{command:m2[1]}).then((r)=>[r.stdout,r.stderr].filter(Boolean).join(`
|
|
3667
|
-
`).trim()).catch(()=>"(error)"))),out=text;for(let i=hits.length-1;i>=0;i--){let m2=hits[i];out=out.slice(0,m2.index)+outs[i]+out.slice(m2.index+m2[0].length)}return out}var import_react13=__toESM(require_react_production(),1);import{EventEmitter as EventEmitter10}from"events";import{homedir}from"os";import{resolve as resolve5,delimiter}from"path";import{existsSync as existsSync3}from"fs";var LOG_MAX=200,LOG_PREVIEW=240,STARTUP_MS=15000,REQUEST_MS=120000;function hermesAgentRoot(){if(process.env.HERMES_AGENT_ROOT)return process.env.HERMES_AGENT_ROOT;let homePath=`${process.env.HOME||homedir()}/.hermes/hermes-agent`;if(existsSync3(homePath))return homePath;let fhs="/usr/local/lib/hermes-agent";if(existsSync3(fhs))return fhs;return homePath}function python(root,platform=process.platform){let env2=process.env.HERMES_PYTHON?.trim();if(env2)return env2;let venv=process.env.VIRTUAL_ENV?.trim();return(platform==="win32"?[venv&&resolve5(venv,"Scripts","python.exe"),resolve5(root,"venv","Scripts","python.exe"),resolve5(root,".venv","Scripts","python.exe")]:[venv&&resolve5(venv,"bin","python"),venv&&resolve5(venv,"bin","python3"),resolve5(root,"venv","bin","python"),resolve5(root,"venv","bin","python3"),resolve5(root,".venv","bin","python"),resolve5(root,".venv","bin","python3")]).find((p)=>p&&existsSync3(p))||(platform==="win32"?"python":"python3")}function asEvent(v2){if(v2&&typeof v2==="object"&&!Array.isArray(v2)&&typeof v2.type==="string")return v2;return null}async function lines(stream,cb){let reader=stream.getReader(),decoder2=new TextDecoder,buf="";try{while(!0){let{done,value}=await reader.read();if(done)break;buf+=decoder2.decode(value,{stream:!0});let parts=buf.split(`
|
|
3667
|
+
`).trim()).catch(()=>"(error)"))),out=text;for(let i=hits.length-1;i>=0;i--){let m2=hits[i];out=out.slice(0,m2.index)+outs[i]+out.slice(m2.index+m2[0].length)}return out}var import_react13=__toESM(require_react_production(),1);import{EventEmitter as EventEmitter10}from"events";import{homedir}from"os";import{resolve as resolve5,delimiter}from"path";import{existsSync as existsSync3}from"fs";var BAD=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDFFF]/g;function scalar(s){let count2=0;return{text:s.replace(BAD,(m2)=>{if(m2.length===2)return m2;return count2+=1,"\uFFFD"}),count:count2}}function encode(v2){let paths=new WeakMap,issues=[];return{text:JSON.stringify(v2,function(key,value){let holder=this&&typeof this==="object"?paths.get(this):void 0,path6=key?`${holder??"$"}.${key}`:"$";if(value&&typeof value==="object")paths.set(value,path6);if(typeof value!=="string")return value;let next=scalar(value);if(next.count>0)issues.push({path:path6,count:next.count});return next.text})??"null",issues}}var LOG_MAX=200,LOG_PREVIEW=240,STARTUP_MS=15000,REQUEST_MS=120000;function hermesAgentRoot(){if(process.env.HERMES_AGENT_ROOT)return process.env.HERMES_AGENT_ROOT;let homePath=`${process.env.HOME||homedir()}/.hermes/hermes-agent`;if(existsSync3(homePath))return homePath;let fhs="/usr/local/lib/hermes-agent";if(existsSync3(fhs))return fhs;return homePath}function python(root,platform=process.platform){let env2=process.env.HERMES_PYTHON?.trim();if(env2)return env2;let venv=process.env.VIRTUAL_ENV?.trim();return(platform==="win32"?[venv&&resolve5(venv,"Scripts","python.exe"),resolve5(root,"venv","Scripts","python.exe"),resolve5(root,".venv","Scripts","python.exe")]:[venv&&resolve5(venv,"bin","python"),venv&&resolve5(venv,"bin","python3"),resolve5(root,"venv","bin","python"),resolve5(root,"venv","bin","python3"),resolve5(root,".venv","bin","python"),resolve5(root,".venv","bin","python3")]).find((p)=>p&&existsSync3(p))||(platform==="win32"?"python":"python3")}function asEvent(v2){if(v2&&typeof v2==="object"&&!Array.isArray(v2)&&typeof v2.type==="string")return v2;return null}async function lines(stream,cb){let reader=stream.getReader(),decoder2=new TextDecoder,buf="";try{while(!0){let{done,value}=await reader.read();if(done)break;buf+=decoder2.decode(value,{stream:!0});let parts=buf.split(`
|
|
3668
3668
|
`);buf=parts.pop()||"";for(let line of parts)if(line)cb(line)}if(buf.trim())cb(buf)}catch{}}class GatewayClient extends EventEmitter10{proc=null;id=0;logs=[];pending=new Map;buf=[];exit;ok=!1;timer=null;sub=!1;root(){return hermesAgentRoot()}push(ev){if(ev.type==="gateway.ready"){if(this.ok=!0,this.timer)clearTimeout(this.timer),this.timer=null}if(this.sub)return void this.emit("event",ev);this.buf.push(ev)}log(line){if(this.logs.push(line)>LOG_MAX)this.logs.splice(0,this.logs.length-LOG_MAX)}dispatch(msg){let id=msg.id,p=id?this.pending.get(id):void 0;if(p){if(this.pending.delete(id),msg.error){let err=msg.error;p.reject(Error(typeof err?.message==="string"?err.message:"request failed"))}else p.resolve(msg.result);return}if(msg.method==="event"){let ev=asEvent(msg.params);if(ev)this.push(ev)}}fail(err){for(let p of this.pending.values())p.reject(err);this.pending.clear()}start(){let root=this.root(),bin=python(root),cwd=process.env.HERMES_CWD||process.cwd(),env2={...process.env};if(!env2.TERMINAL_CWD)env2.TERMINAL_CWD=cwd;let pp=env2.PYTHONPATH?.trim();if(env2.PYTHONPATH=pp?`${root}${delimiter}${pp}`:root,this.ok=!1,this.buf=[],this.exit=void 0,this.proc)try{this.proc.kill()}catch{}if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(()=>{if(this.ok)return;this.log(`[startup] timed out (python=${bin}, cwd=${cwd})`),this.push({type:"gateway.start_timeout",payload:{cwd,python:bin}})},STARTUP_MS);let proc=Bun.spawn([bin,"-u","-m","tui_gateway.entry"],{cwd,env:env2,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(this.proc=proc,this.proc.stdout)lines(this.proc.stdout,(raw)=>{try{this.dispatch(JSON.parse(raw))}catch{let preview=raw.trim().slice(0,LOG_PREVIEW)||"(empty)";this.log(`[protocol] malformed: ${preview}`),this.push({type:"gateway.protocol_error",payload:{preview}})}});if(this.proc.stderr)lines(this.proc.stderr,(raw)=>{let line=raw.trim();if(!line)return;this.log(line),this.push({type:"gateway.stderr",payload:{line}})});proc.exited.then((code)=>{if(this.proc!==proc)return;if(this.timer)clearTimeout(this.timer),this.timer=null;if(this.fail(Error(`gateway exited${code===null?"":` (${code})`}`)),this.sub)this.emit("exit",code);else this.exit=code})}drain(){if(this.sub)return;this.sub=!0;for(let ev of this.buf.splice(0))this.emit("event",ev);if(this.exit!==void 0){let code=this.exit;this.exit=void 0,this.emit("exit",code)}}tail(n=20){return this.logs.slice(-Math.max(1,n)).join(`
|
|
3669
|
-
`)}sid="";setSession(sid){this.sid=sid}request(method,params={}){if(!this.proc||this.proc.exitCode!==null)this.start();let stdin=this.proc?.stdin;if(!stdin||typeof stdin==="number")return Promise.reject(Error("gateway not running"));let rid=`r${++this.id}`,writer=stdin,merged=this.sid&¶ms.session_id===void 0?{session_id:this.sid,...params}:params;return new Promise((resolve4,reject)=>{let timeout=setTimeout(()=>{if(this.pending.delete(rid))reject(Error(`timeout: ${method}`))},REQUEST_MS);this.pending.set(rid,{reject:(e)=>{clearTimeout(timeout),reject(e)},resolve:(v2)=>{clearTimeout(timeout),resolve4(v2)}});try{
|
|
3669
|
+
`)}sid="";setSession(sid){this.sid=sid}request(method,params={}){if(!this.proc||this.proc.exitCode!==null)this.start();let stdin=this.proc?.stdin;if(!stdin||typeof stdin==="number")return Promise.reject(Error("gateway not running"));let rid=`r${++this.id}`,writer=stdin,merged=this.sid&¶ms.session_id===void 0?{session_id:this.sid,...params}:params;return new Promise((resolve4,reject)=>{let timeout=setTimeout(()=>{if(this.pending.delete(rid))reject(Error(`timeout: ${method}`))},REQUEST_MS);this.pending.set(rid,{reject:(e)=>{clearTimeout(timeout),reject(e)},resolve:(v2)=>{clearTimeout(timeout),resolve4(v2)}});try{let frame=encode({jsonrpc:"2.0",id:rid,method,params:merged});if(frame.issues.length){let detail=frame.issues.map((x2)=>`${x2.path}:${x2.count}`).join(", ");this.log(`[wire] sanitized invalid unicode for ${method}: ${detail}`)}writer.write(frame.text+`
|
|
3670
3670
|
`)}catch(e){clearTimeout(timeout),this.pending.delete(rid),reject(e instanceof Error?e:Error(String(e)))}})}kill(){this.proc?.kill()}get ready(){return this.ok}}var Gw=import_react13.createContext(null),GatewayProvider=({client,children})=>{let ref=import_react13.useRef(null);if(!ref.current)ref.current=client??new GatewayClient;let[ready,setReady]=import_react13.useState(ref.current.ready);import_react13.useEffect(()=>{let c=ref.current,onEvent=(ev)=>{if(ev.type==="gateway.ready"||ev.type==="session.info")setReady(!0)};return c.on("event",onEvent),c.start(),c.drain(),()=>{c.off("event",onEvent),c.removeAllListeners(),c.kill()}},[]);let restart=import_react13.useCallback(()=>{setReady(!1),ref.current.start()},[]),value=import_react13.useMemo(()=>({client:ref.current,ready,restart}),[ready,restart]);return $jsx(Gw.Provider,{value,children})};function useGateway(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGateway() must be inside <GatewayProvider>");return ctx.client}function useGatewayEvent(handler){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayEvent() must be inside <GatewayProvider>");let ref=import_react13.useRef(handler);ref.current=handler,import_react13.useEffect(()=>{let c=ctx.client,fn=(ev)=>ref.current(ev);return c.on("event",fn),c.drain(),()=>{c.off("event",fn)}},[ctx.client])}function useGatewayReady(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayReady() must be inside <GatewayProvider>");return ctx.ready}function useGatewayRestart(){let ctx=import_react13.useContext(Gw);if(!ctx)throw Error("useGatewayRestart() must be inside <GatewayProvider>");return ctx.restart}function text(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function mid(){return`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var pn=0;function pid(){return`p${++pn}`}var import_react22=__toESM(require_react_production(),1);var import_react21=__toESM(require_react_production(),1);var import_react17=__toESM(require_react_production(),1);var import_react16=__toESM(require_react_production(),1);var import_react14=__toESM(require_react_production(),1);function makeUse(ctx,name){return()=>{let v2=import_react14.useContext(ctx);if(v2===null)throw Error(`${name}() must be used inside its provider`);return v2}}function resolveTheme(theme,mode){let defs=theme.defs??{};function resolve4(c,chain=[]){if(c instanceof RGBA)return c;if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA.fromHex(c);if(chain.includes(c))throw Error(`Circular color reference: ${[...chain,c].join(" -> ")}`);let next=defs[c]??theme.theme[c];if(next===void 0)throw Error(`Color reference "${c}" not found in defs or theme`);return resolve4(next,[...chain,c])}if(typeof c==="number")return ansiToRgba(c);return resolve4(c[mode],chain)}let resolved=Object.fromEntries(Object.entries(theme.theme).filter(([key])=>key!=="selectedListItemText"&&key!=="backgroundMenu"&&key!=="thinkingOpacity").map(([key,value])=>[key,resolve4(value)])),hasList=theme.theme.selectedListItemText!==void 0;resolved.selectedListItemText=hasList?resolve4(theme.theme.selectedListItemText):resolved.background,resolved.backgroundMenu=theme.theme.backgroundMenu!==void 0?resolve4(theme.theme.backgroundMenu):resolved.backgroundElement;let base={...resolved,_hasSelectedListItemText:hasList,thinkingOpacity:theme.theme.thinkingOpacity??0.6},herm=resolveHermTokens(resolved.accent);return{...base,...herm}}function resolveHermTokens(accent){return{hermAvatar:accent}}function ansiToRgba(code){if(code<16){let colors=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff"];return RGBA.fromHex(colors[code]??"#000000")}if(code<232){let idx=code-16,val=(x2)=>x2===0?0:x2*40+55;return RGBA.fromInts(val(Math.floor(idx/36)),val(Math.floor(idx/6)%6),val(idx%6))}if(code<256){let gray=(code-232)*10+8;return RGBA.fromInts(gray,gray,gray)}return RGBA.fromInts(0,0,0)}var PREVIEW={ares:{primary:"#C7A96B",accent:"#DD4A3A",background:"#2A1212"},aura:{primary:"#a277ff",accent:"#a277ff",background:"#0f0f0f"},ayu:{primary:"#59C2FF",accent:"#E6B450",background:"#0B0E14"},carbonfox:{primary:"#33b1ff",accent:"#ff7eb6",background:"#161616"},"catppuccin-frappe":{primary:"#8da4e2",accent:"#f4b8e4",background:"#303446"},"catppuccin-macchiato":{primary:"#8aadf4",accent:"#f5bde6",background:"#24273a"},catppuccin:{primary:"#89b4fa",accent:"#f5c2e7",background:"#1e1e2e"},charizard:{primary:"#FFD39A",accent:"#F29C38",background:"#2B160E"},cobalt2:{primary:"#0088ff",accent:"#2affdf",background:"#193549"},cursor:{primary:"#88c0d0",accent:"#88c0d0",background:"#181818"},daylight:{primary:"#233662",accent:"#597FE9",background:"#101014"},default:{primary:"#FFD700",accent:"#FFBF00",background:"#1a1a2e"},dracula:{primary:"#bd93f9",accent:"#8be9fd",background:"#282a36"},everforest:{primary:"#a7c080",accent:"#d699b6",background:"#2d353b"},flexoki:{primary:"#DA702C",accent:"#8B7EC8",background:"#100F0F"},github:{primary:"#58a6ff",accent:"#39c5cf",background:"#0d1117"},gruvbox:{primary:"#83a598",accent:"#8ec07c",background:"#282828"},kanagawa:{primary:"#7E9CD8",accent:"#D27E99",background:"#1F1F28"},"lucent-orng":{primary:"#EC5B2B",accent:"#FFF7F1",background:"transparent"},material:{primary:"#82aaff",accent:"#89ddff",background:"#263238"},matrix:{primary:"#2eff6a",accent:"#c770ff",background:"#0a0e0a"},mercury:{primary:"#8da4f5",accent:"#8da4f5",background:"#171721"},mono:{primary:"#e6edf3",accent:"#aaaaaa",background:"#1F1F1F"},monokai:{primary:"#66d9ef",accent:"#a6e22e",background:"#272822"},nightowl:{primary:"#82AAFF",accent:"#c792ea",background:"#011627"},nord:{primary:"#88C0D0",accent:"#8FBCBB",background:"#2E3440"},"one-dark":{primary:"#61afef",accent:"#56b6c2",background:"#282c34"},opencode:{primary:"#fab283",accent:"#9d7cd8",background:"#0a0a0a"},orng:{primary:"#EC5B2B",accent:"#FFF7F1",background:"#0a0a0a"},"osaka-jade":{primary:"#2DD5B7",accent:"#549e6a",background:"#111c18"},palenight:{primary:"#82aaff",accent:"#89ddff",background:"#292d3e"},poseidon:{primary:"#A9DFFF",accent:"#5DB8F5",background:"#0F2440"},rosepine:{primary:"#9ccfd8",accent:"#ebbcba",background:"#191724"},sisyphus:{primary:"#F5F5F5",accent:"#E7E7E7",background:"#202020"},slate:{primary:"#7eb8f6",accent:"#8EA8FF",background:"#151C2F"},solarized:{primary:"#268bd2",accent:"#2aa198",background:"#002b36"},synthwave84:{primary:"#36f9f6",accent:"#b084eb",background:"#262335"},tokyonight:{primary:"#82aaff",accent:"#ff966c",background:"#1a1b26"},vercel:{primary:"#0070F3",accent:"#8E4EC6",background:"#000000"},vesper:{primary:"#FFC799",accent:"#FFC799",background:"#101010"},"warm-lightmode":{primary:"#9D681D",accent:"#CE661C",background:"#101014"},zenburn:{primary:"#8cd0d3",accent:"#93e0e3",background:"#3f3f3f"}},NAMES=Object.keys(PREVIEW).sort();var cache=new Map,pending=new Map;async function load(name){let hit=cache.get(name);if(hit)return hit;let inflight=pending.get(name);if(inflight)return inflight;if(!PREVIEW[name])throw Error(`Unknown theme: ${name}`);let p=import(`./themes/${name}.json`).then((m2)=>{let json=m2.default??m2;return cache.set(name,json),pending.delete(name),json});return pending.set(name,p),p}function get(name){return cache.get(name)}async function prime(name){await load(name).catch(()=>{return})}var DEFAULT_THEME="tokyonight",THEME_NAMES=NAMES;function syntax(theme){return SyntaxStyle.fromTheme(rules(theme))}function rules(theme){return[{scope:["default"],style:{foreground:theme.text}},{scope:["comment","comment.documentation"],style:{foreground:theme.syntaxComment,italic:!0}},{scope:["string","symbol"],style:{foreground:theme.syntaxString}},{scope:["number","boolean"],style:{foreground:theme.syntaxNumber}},{scope:["keyword"],style:{foreground:theme.syntaxKeyword,italic:!0}},{scope:["keyword.return","keyword.conditional","keyword.repeat"],style:{foreground:theme.syntaxKeyword,italic:!0}},{scope:["keyword.type"],style:{foreground:theme.syntaxType,bold:!0}},{scope:["keyword.function","function.method"],style:{foreground:theme.syntaxFunction}},{scope:["function","function.call"],style:{foreground:theme.syntaxFunction}},{scope:["variable","variable.parameter"],style:{foreground:theme.syntaxVariable}},{scope:["type"],style:{foreground:theme.syntaxType}},{scope:["operator"],style:{foreground:theme.syntaxOperator}},{scope:["punctuation","punctuation.bracket","punctuation.delimiter"],style:{foreground:theme.syntaxPunctuation}},{scope:["markup.heading"],style:{foreground:theme.markdownHeading,bold:!0}},{scope:["markup.strong"],style:{foreground:theme.markdownStrong,bold:!0}},{scope:["markup.italic"],style:{foreground:theme.markdownEmph,italic:!0}},{scope:["markup.link"],style:{foreground:theme.markdownLink,underline:!0}},{scope:["markup.raw"],style:{foreground:theme.markdownCode}},{scope:["markup.list"],style:{foreground:theme.markdownListItem}}]}var exports_preferences={};__export(exports_preferences,{usePref:()=>usePref,set:()=>set,reset:()=>reset,reload:()=>reload,prefs:()=>exports_preferences,load:()=>load2,get:()=>get2});var import_react15=__toESM(require_react_production(),1);import{join as join5}from"path";import{existsSync as existsSync6,mkdirSync as mkdirSync2,readFileSync,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir2}from"os";import{join as join4}from"path";import{existsSync as existsSync5,mkdirSync,readdirSync,renameSync}from"fs";var HOME=()=>process.env.HOME||homedir2(),HERMES_HOME=()=>process.env.HERMES_HOME||join4(HOME(),".hermes"),migrated=!1;function configDir(){let dir=process.env.HERM_CONFIG_DIR||join4(HERMES_HOME(),"herm");if(!migrated)migrated=!0,maybeMigrateLegacy(dir);return dir}function maybeMigrateLegacy(target){if(process.env.HERM_CONFIG_DIR)return;let legacy=join4(HOME(),".config","herm");if(!existsSync5(legacy)||legacy===target)return;try{if(existsSync5(target)&&readdirSync(target).length>0)return;mkdirSync(target,{recursive:!0});for(let name of readdirSync(legacy)){let src=join4(legacy,name),dst=join4(target,name);if(existsSync5(dst))continue;try{renameSync(src,dst)}catch{}}}catch{}}var DEFAULTS={mouse:!0,targetFps:30};function configFile(){return join5(configDir(),"tui.json")}var cached=null;function reset(){cached=null}function reload(){cached=null;for(let l of listeners)l()}function load2(){if(cached)return cached;let CONFIG_FILE=configFile();try{if(!existsSync6(CONFIG_FILE)){let prefs2={...DEFAULTS};return cached=prefs2,prefs2}let raw=JSON.parse(readFileSync(CONFIG_FILE,"utf-8"));if(raw.eikonPath&&!raw.eikon)raw.eikon=raw.eikonPath.split("/").pop()?.replace(/\.eikon$/,""),delete raw.eikonPath;let prefs={...DEFAULTS,...raw};return cached=prefs,prefs}catch{let prefs={...DEFAULTS};return cached=prefs,prefs}}function save(partial){let current=load2();if(partial)Object.assign(current,partial);cached=current;try{let CONFIG_DIR=configDir();if(!existsSync6(CONFIG_DIR))mkdirSync2(CONFIG_DIR,{recursive:!0});let json=JSON.stringify(current,null,2)+`
|
|
3671
3671
|
`;writeFileSync2(configFile(),json,"utf-8")}catch(err){if(process.env.PERF)console.error("[preferences] failed to save:",err)}}function get2(key){return load2()[key]}function set(key,value){if(load2()[key]===value)return;save({[key]:value});for(let l of listeners)l()}var listeners=new Set;function subscribe(l){return listeners.add(l),()=>listeners.delete(l)}function usePref(key){return import_react15.useSyncExternalStore(subscribe,()=>load2()[key])}var Ctx=import_react16.createContext(null),THEMES_SET=new Set(THEME_NAMES),ThemeProvider=({children,initial,mode:initialMode="dark"})=>{let pref=usePref("theme"),modePref=usePref("themeMode"),active=pref??initial??DEFAULT_THEME,mode=modePref==="light"||modePref==="dark"?modePref:initialMode,[tick,force]=import_react16.useState(0);import_react16.useEffect(()=>{if(get(active)&&get(DEFAULT_THEME))return;let cancelled=!1,need=[active,DEFAULT_THEME].filter((n)=>!get(n));return Promise.all(need.map((n)=>load(n).catch(()=>{return}))).then(()=>{if(!cancelled)force((n)=>n+1)}),()=>{cancelled=!0}},[active]);let resolved=import_react16.useMemo(()=>{let json=get(active)??get(DEFAULT_THEME);if(!json)return null;try{return resolveTheme(json,mode)}catch{let fallback=get(DEFAULT_THEME);return fallback?resolveTheme(fallback,mode):null}},[active,mode,tick]),set2=import_react16.useCallback((name)=>{if(!THEMES_SET.has(name))return!1;if(set("theme",name),!get(name))load(name).catch(()=>{});return!0},[]),setMode=import_react16.useCallback((mode2)=>{set("themeMode",mode2)},[]),has=import_react16.useCallback((name)=>THEMES_SET.has(name),[]),syntaxStyle=import_react16.useMemo(()=>resolved?syntax(resolved):null,[resolved]),value=import_react16.useMemo(()=>{if(!resolved||!syntaxStyle)return null;return{theme:resolved,syntaxStyle,name:active,mode,set:set2,setMode,names:THEME_NAMES,has}},[resolved,syntaxStyle,active,mode,set2,setMode,has]);if(!value)return null;return $jsx(Ctx.Provider,{value,children})},useTheme=makeUse(Ctx,"useTheme");var ANSI2=new RegExp(["\\x1B\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]","\\x1B\\[[\\x30-\\x3F]*[\\x20-\\x2F]*","\\x1B\\][^\\x07\\x1B]*(?:\\x07|\\x1B\\\\)?","\\x1B[PX^_][^\\x1B]*(?:\\x1B\\\\)?","\\x1B[\\x20-\\x7E]","\\x1B"].join("|"),"g"),CTRL=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g;function sanitize(s){if(!s)return"";return s.replace(ANSI2,"").replace(CTRL,"")}function isDiff(s){if(!s)return!1;return/^--- a\//m.test(s)||/^@@ /m.test(s)||/^diff --git /m.test(s)}var CAP=80,WORD_CAP=40,tokens=(s)=>s.split(/(\s+)/).filter((t2)=>t2.length>0);function wordDiff(a,b2){let ta=tokens(a),tb=tokens(b2),p=0;while(p<ta.length&&p<tb.length&&ta[p]===tb[p])p++;let s=0;while(s<ta.length-p&&s<tb.length-p&&ta[ta.length-1-s]===tb[tb.length-1-s])s++;let seg=(t2)=>{let mid2=t2.slice(p,t2.length-s).join(""),out=[];if(p)out.push({text:t2.slice(0,p).join(""),hi:!1});if(mid2)out.push({text:mid2,hi:!0});if(s)out.push({text:t2.slice(t2.length-s).join(""),hi:!1});return out};return[seg(ta),seg(tb)]}function intraline(rows){let marks=rows.map(()=>null);if(rows.length>WORD_CAP)return marks;let del=(l)=>l.startsWith("-")&&!l.startsWith("---"),add=(l)=>l.startsWith("+")&&!l.startsWith("+++"),i=0;while(i<rows.length){if(!del(rows[i])){i++;continue}let j2=i;while(j2<rows.length&&del(rows[j2]))j2++;let k2=j2;while(k2<rows.length&&add(rows[k2]))k2++;let n=Math.min(j2-i,k2-j2);for(let d2=0;d2<n;d2++){let[rm,ad]=wordDiff(rows[i+d2].slice(1),rows[j2+d2].slice(1));marks[i+d2]=rm,marks[j2+d2]=ad}i=k2}return marks}var DiffBlock=import_react17.memo(({text:text2})=>{let theme=useTheme().theme,all=sanitize(text2).replace(/\n$/,"").split(`
|
|
3672
3672
|
`),rows=all.slice(0,CAP),more=all.length-rows.length,marks=intraline(rows),fg2=(l)=>l.startsWith("@@")?theme.accent:l.startsWith("+++")||l.startsWith("---")?theme.textMuted:l.startsWith("+")?theme.success:l.startsWith("-")?theme.error:theme.textMuted;return $jsxs("box",{flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[rows.map((l,i)=>{let segs=marks[i],bg2=l.startsWith("+")?theme.diffAddedBg:theme.diffRemovedBg;return $jsx("box",{height:1,overflow:"hidden",minWidth:0,children:$jsx("text",{fg:fg2(l),children:segs?$jsxs($Fragment,{children:[l[0],segs.map((s,j2)=>s.hi?$jsx("span",{bg:bg2,children:s.text},j2):s.text)]}):l||" "})},i)}),more>0?$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2026 ",more," more lines"]})}):null]})});var import_react19=__toESM(require_react_production(),1);var import_react18=__toESM(require_react_production(),1);var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],MS=80,subs=new Set,tick=0,timer=null;function sub(fn){if(subs.add(fn),fn(tick),!timer)timer=setInterval(()=>{tick=(tick+1)%FRAMES.length;for(let s of Array.from(subs))s(tick)},MS);return()=>{if(subs.delete(fn),subs.size===0&&timer)clearInterval(timer),timer=null}}function useGlyph(active){let ref=import_react18.useRef(null);return import_react18.useEffect(()=>{if(!active)return;return sub((n)=>{let node=ref.current;if(node)node.children=[FRAMES[n]]})},[active]),ref}var Spinner=import_react18.memo((props)=>{let theme=useTheme().theme,color=props.color??theme.textMuted,on=exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsxs("text",{children:[$jsx("span",{ref,fg:color,children:on?FRAMES[tick]:"\u22EF"}),props.label?$jsxs("span",{fg:color,children:[" ",props.label]}):null]})}),SpinGlyph=import_react18.memo((props)=>{let on=(props.active??!0)&&exports_preferences.get("animations")!==!1,ref=useGlyph(on);return $jsx("span",{ref,fg:props.fg,children:on?FRAMES[tick]:"\u22EF"})});function useSpinnerGlyph(active=!0){let on=exports_preferences.get("animations")!==!1&&active,[n,set2]=import_react18.useState(tick);return import_react18.useEffect(()=>on?sub(set2):void 0,[on]),on?FRAMES[n]:"\u22EF"}var SPEC={terminal:{icon:"$",verb:"",pending:"Writing command\u2026"},process:{icon:"\u229A",verb:"Process",pending:"Managing process\u2026"},execute_code:{icon:"\xBB",verb:"Exec",pending:"Writing script\u2026"},read_file:{icon:"\u2192",verb:"Read",pending:"Reading file\u2026"},write_file:{icon:"\u2190",verb:"Write",pending:"Preparing write\u2026"},patch:{icon:"\u2190",verb:"Edit",pending:"Preparing edit\u2026"},search_files:{icon:"\u2731",verb:"Search",pending:"Searching\u2026"},web_search:{icon:"\u25C8",verb:"Web",pending:"Searching web\u2026"},web_extract:{icon:"%",verb:"Fetch",pending:"Fetching page\u2026"},session_search:{icon:"\u21BA",verb:"Recall",pending:"Searching memory\u2026"},browser_navigate:{icon:"%",verb:"Navigate",pending:"Navigating\u2026"},browser_click:{icon:"\xB7",verb:"Click",pending:"Clicking\u2026"},browser_type:{icon:"\u2328",verb:"Type",pending:"Typing\u2026"},browser_snapshot:{icon:"\u2399",verb:"Snapshot",pending:"Capturing\u2026"},browser_vision:{icon:"\u25C9",verb:"Vision",pending:"Looking\u2026"},vision_analyze:{icon:"\u25C9",verb:"Vision",pending:"Analyzing image\u2026"},todo:{icon:"\u2630",verb:"Todo",pending:"Updating todos\u2026"},memory:{icon:"\u2691",verb:"Memory",pending:"Updating memory\u2026"},clarify:{icon:"?",verb:"Ask",pending:"Asking\u2026"},skill_view:{icon:"\u25C6",verb:"Skill",pending:"Loading skill\u2026"},skills_list:{icon:"\u25C6",verb:"Skills",pending:"Listing skills\u2026"},skill_manage:{icon:"\u25C6",verb:"Skill",pending:"Managing skill\u2026"},delegate_task:{icon:"\u2299",verb:"Delegate",pending:"Spawning agent\u2026"},cronjob:{icon:"\u25F7",verb:"Cron",pending:"Managing cron\u2026"},text_to_speech:{icon:"\u266A",verb:"TTS",pending:"Synthesizing\u2026"},image_generate:{icon:"\u2726",verb:"Image",pending:"Generating image\u2026"},video_generate:{icon:"\u2726",verb:"Video",pending:"Generating video\u2026"}},GENERIC={icon:"\u2699",verb:"",pending:"Running\u2026"};function spec(name){if(name.startsWith("subagent"))return{icon:"\u2299",verb:"Subagent",pending:"Running\u2026"};if(name.startsWith("mcp__")||name.startsWith("mcp:"))return{icon:"\u25C7",verb:"MCP",pending:"Calling\u2026"};return SPEC[name]??GENERIC}function ms(d2){if(d2==null)return"";if(d2<1000)return`${Math.round(d2)}ms`;if(d2<60000)return`${(d2/1000).toFixed(1)}s`;return`${Math.floor(d2/60000)}m${Math.round(d2%60000/1000)}s`}var lead=(branch)=>branch==="mid"?"\u251C\u2500 ":"\u2514\u2500 ",rail=(branch)=>branch==="mid"?"\u2502 ":" ",DetailRow=import_react19.memo((p)=>{let theme=useTheme().theme,fg2=p.detail.tone==="error"?theme.error:theme.textMuted,stem=rail(p.branch),fork=p.last?"\u2514\u2500 ":"\u251C\u2500 ",pad=p.last?" ":"\u2502 ",lines2=p.detail.text.replace(/\t/g," ").split(`
|
|
@@ -3674,7 +3674,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
3674
3674
|
\u2026`;if(raw[i]===`
|
|
3675
3675
|
`&&++n>LINES)return`${raw.slice(0,i).trimEnd()}
|
|
3676
3676
|
\u2026`}return raw}function lines2(s){let n=1;for(let i=0;i<s.length;i++)if(s[i]===`
|
|
3677
|
-
`&&++n>=5)return 6;return n+1}var Inline=import_react21.memo(({branch,details,tool})=>{let s=spec(tool.name),body=tool.preview&&!isDiff(tool.preview)?short(tool.preview):"",label=s.verb&&body?`${s.verb} ${body}`:body||s.verb||tool.name;return $jsx(InlineTool,{branch,part:tool,complete:!!body||tool.status!=="running",details,children:label})});function visible(tool,mode){return mode!=="hidden"||tool.status==="running"}function details(tool,mode){let full=tool.verboseResult&&!isDiff(tool.verboseResult)?tool.verboseResult:void 0,sum=tool.result&&!isDiff(tool.result)?tool.result:void 0,err=tool.status==="error"&&(full||sum)?{label:"Error",text:cap(full??sum),tone:"error"}:void 0;if(mode!=="expanded")return err?[err]:[];let out=[];if(tool.verboseArgs)out.push({label:"Args",text:cap(tool.verboseArgs)});if(err)out.push(err);if(tool.verboseResult&&tool.status!=="error"&&!isDiff(tool.verboseResult))out.push({label:"Result",text:cap(tool.verboseResult)});return out}function cost(tool,mode){if(!visible(tool,mode))return 0;if(tool.trail)return 2+Math.min(tool.trail.length,TRAIL);if(tool.name==="delegate_task")return 2;return 1+details(tool,mode).reduce((n,d2)=>n+lines2(d2.text),0)}var Tool=import_react21.memo(({branch,tool,detail="expanded"})=>{let list=import_react21.useMemo(()=>details(tool,detail),[tool,detail]);if(!visible(tool,detail))return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{branch,tool});return $jsx(Inline,{branch,details:list,tool})});var CLOUD_MIN=12,CLOUD_MAX=24,CLOUD={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2504",vertical:"\u2506",topT:"\u2504",bottomT:"\u2504",leftT:"\u2506",rightT:"\u2506",cross:"\u253C"},SLOTS=[["\u256D\u2504\u2504\u256E ","\u2570\u2504\u2504\u256F "],[" \u256D\u256E "," \u2570\u256F "],[" \u2576 "," "]],BLANK=" ",ORDER=[2,1,0,-1],Tail=import_react22.memo((props)=>{let theme=useTheme().theme,refs=import_react22.useRef([]),paint=(lit)=>{SLOTS.forEach((slot,i)=>slot.forEach((l,j2)=>{let node=refs.current[i*2+j2];if(node)node.children=[lit===null||lit===i?l:BLANK]}))};return import_react22.useEffect(()=>{if(!props.run){paint(null);return}let f=0;paint(ORDER[0]);let t2=setInterval(()=>{f=(f+1)%ORDER.length,paint(ORDER[f])},160);return()=>{clearInterval(t2),paint(null)}},[props.run]),$jsx("box",{flexDirection:"column",children:SLOTS.flatMap((slot,i)=>slot.map((l,j2)=>$jsx("text",{fg:theme.hermAvatar,children:$jsx("span",{ref:(el)=>{refs.current[i*2+j2]=el},children:l})},`${i}-${j2}`)))})});function parts(m2){return m2?.parts.filter((p)=>p.type==="thinking"||p.type==="tool")??[]}function latest(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="assistant")return messages[i];return}function rows(list,detail){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"?cost(p,detail):1),0)}var ThoughtCloud=import_react22.memo((props)=>{let{theme,syntaxStyle}=useTheme(),detail=usePref("toolDetails")??"expanded",src=props.pick??latest(props.messages),all=parts(src),think=all.filter((p)=>p.type==="thinking"),seen=all.filter((p)=>p.type==="tool").filter((t2)=>visible(t2,detail)),[pane,setPane]=import_react22.useState("reasoning");import_react22.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&seen.length>0)setPane("tools");if(pane==="tools"&&seen.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,seen.length]);let body=pane==="reasoning"?think:seen,manual=import_react22.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body,detail)+3)),resize=props.onResize;import_react22.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react22.useRef(null),grab=(e)=>{drag.current={y:e.y,h:props.height},manual.current=!0,e.stopPropagation()},move=(e)=>{let d2=drag.current;if(!d2)return;resize(Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,d2.h+(e.y-d2.y))))},drop=()=>{drag.current=null},pill=(id,label,n)=>{let on=pane===id;return $jsx("box",{height:1,marginRight:2,onMouseDown:(e)=>{e.stopPropagation(),setPane(id)},children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:on?$jsx("strong",{children:label}):label}),n!==null&&n>0?$jsx("span",{fg:theme.textMuted,children:` ${n}`}):null]})})};return $jsxs("box",{height:props.height,flexDirection:"column",position:"relative",marginLeft:1,border:!0,borderColor:theme.hermAvatar,customBorderChars:CLOUD,backgroundColor:theme.backgroundPanel,paddingX:1,children:[$jsxs("box",{height:1,flexShrink:0,flexDirection:"row",children:[pill("reasoning","reasoning",null),pill("tools","tools",seen.length),$jsx("box",{flexGrow:1}),detail!=="expanded"?$jsx("box",{marginRight:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u27E8",detail,"\u27E9"]})}):null,props.onClose?$jsx("box",{width:1,onMouseDown:props.onClose,children:$jsx("text",{fg:theme.textMuted,children:"\xD7"})}):null]}),$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:body.map((p,i)=>p.type==="thinking"?$jsx("box",{minHeight:1,width:"100%",flexShrink:0,children:$jsx("markdown",{content:p.content,fg:theme.markdownText,syntaxStyle})},p.key??`th-${i}`):$jsx("box",{width:"100%",flexShrink:0,children:$jsx(Tool,{branch:i===body.length-1?"last":"mid",tool:p,detail})},p.id||`t-${i}`))})}),$jsx("box",{position:"absolute",left:0,right:0,bottom:0,height:1,onMouseDown:grab,onMouseDrag:move,onMouseUp:drop,onMouseDragEnd:drop})]})});var import_react28=__toESM(require_react_production(),1);var import_react23=__toESM(require_react_production(),1);var def=(chord,desc,scope)=>({chord,desc,scope}),DEFAULTS2={leader:def("ctrl+x","Leader prefix","global"),"app.exit":def("ctrl+c","Quit","global"),"input.clear":def("ctrl+c","Clear input","global"),"app.suspend":def("ctrl+z","Suspend to shell","global"),"app.redraw":def("ctrl+l","Clear & force-repaint terminal","global"),"app.sidebar":def("<leader>b","Toggle sidebar","global"),"palette.open":def("ctrl+k","Command palette","global"),"help.open":def("f1","Keyboard shortcuts","global"),"tab.next":def("alt+right","Next tab","global"),"tab.prev":def("alt+left","Previous tab","global"),"focus.cycle":def("tab","Cycle focus (double-tap \u2192 composer)","global"),"editor.open":def("<leader>e,ctrl+g","Open $EDITOR on prompt","global"),"reply.copy":def("<leader>y,ctrl+y","Copy last assistant reply","global"),"clipboard.attach":def("ctrl+v","Attach clipboard image","global"),"queue.flush":def("<leader>u","Interrupt and send queued now","global"),"session.interrupt":def("escape","Interrupt (double-tap while streaming)","global"),"session.new":def("<leader>n","New session","global"),"session.redo":def("<leader>r","Redo last undo","global"),"session.compress":def("<leader>c","Compress context","global"),"session.steer":def("<leader>s","Steer active turn","global"),"input.stash":def("<leader>p","Stash prompt draft","global"),"session.timeline":def("<leader>g","Session timeline","global"),"theme.pick":def("<leader>t","Switch theme","global"),"model.pick":def("<leader>m","Switch model","global"),"status.open":def("<leader>i","Show status","global"),"list.up":def("up","Move selection up","list"),"list.down":def("down","Move selection down","list"),"list.pageUp":def("pageup","Page up","list"),"list.pageDown":def("pagedown","Page down","list"),"list.home":def("home","First item","list"),"list.end":def("end","Last item","list"),"list.activate":def("return","Activate / open","list"),"list.delete":def("d,delete","Delete item","list"),"list.refresh":def("r","Reload","list"),"list.new":def("n","Create","list"),"list.search":def("/","Filter","list"),"list.toggle":def("space","Toggle item","list"),"dialog.accept":def("return","Accept","dialog"),"dialog.cancel":def("escape","Cancel / close","dialog"),"dialog.confirm":def("y","Yes","dialog"),"dialog.deny":def("n","No","dialog"),"dialog.copy":def("c","Copy body","dialog"),"input.submit":def("return","Send","composer"),"input.newline":def("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline","composer"),"sessions.rename":def("ctrl+r","Retitle session","sessions"),"sessions.prev":def("left","Previous source filter","sessions"),"sessions.next":def("right","Next source filter","sessions"),"agents.kill":def("k","Kill subagent","agents"),"agents.history":def("h","Spawn history","agents"),"agents.install":def("i","Install distribution","agents"),"config.save":def("ctrl+s","Write config","config"),"config.mode":def("m","Toggle form \u2194 YAML","config"),"eikon.save":def("ctrl+s","Save eikon","eikon")};var TAB_SCOPES=new Set(["sessions","cron","env","agents","skills","config","eikon"]);function scopesOverlap(a,b2){if(a===b2)return!0;if(a==="global"||b2==="global")return!0;if(a==="list")return TAB_SCOPES.has(b2);if(b2==="list")return TAB_SCOPES.has(a);return!1}var ALIAS={esc:"escape",enter:"return",del:"delete",ins:"insert",space:"space"," ":"space"};function parse2(spec2){if(!spec2||spec2==="none")return[];return spec2.split(",").map(one)}function one(combo){let c={name:"",ctrl:!1,meta:!1,shift:!1,super:!1,leader:!1};for(let raw of combo.replace(/<leader>/g,"leader+").toLowerCase().split("+")){let p=raw.trim();if(!p)continue;if(p==="ctrl")c.ctrl=!0;else if(p==="alt"||p==="meta"||p==="option")c.meta=!0;else if(p==="shift")c.shift=!0;else if(p==="super"||p==="cmd")c.super=!0;else if(p==="leader")c.leader=!0;else c.name=ALIAS[p]??p}return c}function from(key,leader=!1){return{name:key.name===" "?"space":key.name,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super??!1,leader}}function eq(a,b2){return a.name===b2.name&&a.ctrl===b2.ctrl&&a.meta===b2.meta&&a.shift===b2.shift&&a.super===b2.super&&a.leader===b2.leader}function match(list,key,leader=!1){if(list.length===0)return!1;let k2=from(key,leader);return list.some((c)=>eq(c,k2))}function print(list,lead2){let c=list[0];if(!c)return"";let mods=[];if(c.ctrl)mods.push("Ctrl");if(c.meta)mods.push("Alt");if(c.super)mods.push("Super");if(c.shift)mods.push("Shift");let name=LABEL[c.name]??cap2(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead2?`${lead2} ${body}`:`<leader> ${body}`}var LABEL={return:"Enter",escape:"Esc",space:"Space",delete:"Del",backspace:"\u232B",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",pageup:"PgUp",pagedown:"PgDn",home:"Home",end:"End",tab:"Tab"};function cap2(s){return s.length===1?s.toUpperCase():s.charAt(0).toUpperCase()+s.slice(1)}function toBindings(list,action){return list.map((c)=>({name:c.name,ctrl:c.ctrl||void 0,meta:c.meta||void 0,shift:c.shift||void 0,super:c.super||void 0,action}))}function key(c){return`${c.leader?"L":""}${c.ctrl?"C":""}${c.meta?"M":""}${c.shift?"S":""}${c.super?"W":""}-${c.name}`}var LEADER_MS=2000,Ctx2=import_react23.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react23.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead2=table.get("leader"),leadLabel=print(lead2),armed=import_react23.useRef(!1),stolen=import_react23.useRef(null),timer2=import_react23.useRef(null),[,bump]=import_react23.useState(0),disarm=import_react23.useCallback(()=>{if(!armed.current)return;if(armed.current=!1,timer2.current)clearTimeout(timer2.current),timer2.current=null;let f=stolen.current;if(stolen.current=null,f&&!f.isDestroyed&&!renderer.currentFocusedRenderable)f.focus();bump((n)=>n+1)},[renderer]),arm=import_react23.useCallback(()=>{if(armed.current=!0,stolen.current=renderer.currentFocusedRenderable??null,stolen.current?.blur(),timer2.current)clearTimeout(timer2.current);timer2.current=setTimeout(disarm,LEADER_MS),bump((n)=>n+1)},[renderer,disarm]);useKeyboard((key2)=>{if(!armed.current&&match(lead2,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react23.useMemo(()=>({get leader(){return armed.current},match:(id,key2)=>match(table.get(id)??[],key2,armed.current),print:(id)=>print(table.get(id)??[],leadLabel),chord:(id)=>table.get(id)??[],all:(scope)=>Object.keys(DEFAULTS2).filter((id)=>DEFAULTS2[id].scope===scope).map((id)=>({id,desc:DEFAULTS2[id].desc,scope,chord:table.get(id)??[]})),table}),[table,leadLabel]);return $jsx(Ctx2.Provider,{value,children})},useKeys=makeUse(Ctx2,"useKeys");var import_react25=__toESM(require_react_production(),1);function handleListKey(keys,key2,o){let move=(next)=>{o.setSel((p)=>{let n=Math.max(0,Math.min(o.count-1,next(p)));return o.scrollTo?.(n),n})},pg=o.page??10;if(keys.match("list.up",key2))return move((p)=>p-1),!0;if(keys.match("list.down",key2))return move((p)=>p+1),!0;if(keys.match("list.pageUp",key2))return move((p)=>p-pg),!0;if(keys.match("list.pageDown",key2))return move((p)=>p+pg),!0;if(keys.match("list.home",key2))return move(()=>0),!0;if(keys.match("list.end",key2))return move(()=>o.count-1),!0;if(o.onActivate&&keys.match("list.activate",key2))return o.onActivate(),!0;if(o.onDelete&&keys.match("list.delete",key2))return o.onDelete(),!0;if(o.onRefresh&&keys.match("list.refresh",key2))return o.onRefresh(),!0;if(o.onNew&&keys.match("list.new",key2))return o.onNew(),!0;if(o.onToggle&&keys.match("list.toggle",key2))return o.onToggle(),!0;if(o.onSearch&&keys.match("list.search",key2))return o.onSearch(),!0;return!1}function useListKeys(o){let keys=useKeys();return useKeyboard((key2)=>{if(!(typeof o.active==="function"?o.active():o.active))return;if(handleListKey(keys,key2,o))return;o.also?.(key2,keys)}),keys}function useFollow(prefix,key2){let ref=import_react25.useRef(null),id=(i)=>`${prefix}-row-${key2?.(i)??i}`;return{ref,id,opts:{scrollTo:(n)=>ref.current?.scrollChildIntoView(id(n)),get page(){return Math.max(1,(ref.current?.viewport.height??10)-1)}}}}function conflicts(table){let buckets=new Map;for(let[id,chords]of table)for(let c of chords){let k2=key(c),b2=buckets.get(k2);if(b2)b2.push([id,c]);else buckets.set(k2,[[id,c]])}let out=[];for(let bucket of buckets.values()){if(bucket.length<2)continue;for(let i=0;i<bucket.length;i++)for(let j2=i+1;j2<bucket.length;j2++){let[a,c]=bucket[i],[b2]=bucket[j2];if(scopesOverlap(DEFAULTS2[a].scope,DEFAULTS2[b2].scope))out.push({chord:c,a,b:b2})}}return out}function conflictsWith(table,id){let mine=new Set((table.get(id)??[]).map(key));if(mine.size===0)return[];let scope=DEFAULTS2[id].scope,out=[];for(let[other,chords]of table){if(other===id)continue;if(!scopesOverlap(scope,DEFAULTS2[other].scope))continue;if(chords.some((c)=>mine.has(key(c))))out.push(other)}return out}var import_react27=__toESM(require_react_production(),1);var TabStrip=import_react27.memo(({tabs,active,onChange,hint})=>{let theme=useTheme().theme;return $jsxs("box",{width:"100%",flexDirection:"row",height:1,overflow:"hidden",children:[tabs.map((name,i)=>$jsx("box",{onMouseDown:()=>onChange(i),paddingX:2,marginRight:1,flexShrink:0,backgroundColor:i===active?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===active?theme.primary:theme.textMuted,children:$jsx("strong",{children:name})})},i)),$jsx("box",{flexGrow:1,minWidth:0}),hint?$jsx("box",{paddingX:1,flexShrink:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.borderSubtle,children:hint})}):null]})});var TabBar=import_react28.memo(({tabs,activeTab,onTabChange})=>{let keys=useKeys(),hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} or ${keys.print("leader")} N`;return $jsx(TabStrip,{tabs:tabs.map((t2)=>t2.name),active:activeTab,onChange:onTabChange,hint})});var import_react33=__toESM(require_react_production(),1);var import_react29=__toESM(require_react_production(),1);var default_default=`{"type":"header","asset":{"version":"2.0","minVersion":"2.0","width":48,"height":24,"mediaType":"application/vnd.eikon.stream+jsonl"},"name":"nous-girl"}
|
|
3677
|
+
`&&++n>=5)return 6;return n+1}var Inline=import_react21.memo(({branch,details,tool})=>{let s=spec(tool.name),body=tool.preview&&!isDiff(tool.preview)?short(tool.preview):"",label=s.verb&&body?`${s.verb} ${body}`:body||s.verb||tool.name;return $jsx(InlineTool,{branch,part:tool,complete:!!body||tool.status!=="running",details,children:label})});function visible(tool,mode){return mode!=="hidden"||tool.status==="running"}function details(tool,mode){let full=tool.verboseResult&&!isDiff(tool.verboseResult)?tool.verboseResult:void 0,sum=tool.result&&!isDiff(tool.result)?tool.result:void 0,err=tool.status==="error"&&(full||sum)?{label:"Error",text:cap(full??sum),tone:"error"}:void 0;if(mode!=="expanded")return err?[err]:[];let out=[];if(tool.verboseArgs)out.push({label:"Args",text:cap(tool.verboseArgs)});if(err)out.push(err);if(tool.verboseResult&&tool.status!=="error"&&!isDiff(tool.verboseResult))out.push({label:"Result",text:cap(tool.verboseResult)});return out}function cost(tool,mode){if(!visible(tool,mode))return 0;if(tool.trail)return 2+Math.min(tool.trail.length,TRAIL);if(tool.name==="delegate_task")return 2;return 1+details(tool,mode).reduce((n,d2)=>n+lines2(d2.text),0)}var Tool=import_react21.memo(({branch,tool,detail="expanded"})=>{let list=import_react21.useMemo(()=>details(tool,detail),[tool,detail]);if(!visible(tool,detail))return null;if(tool.trail||tool.name==="delegate_task")return $jsx(Subagent,{branch,tool});return $jsx(Inline,{branch,details:list,tool})});var CLOUD_MIN=12,CLOUD_MAX=24,CLOUD={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2504",vertical:"\u2506",topT:"\u2504",bottomT:"\u2504",leftT:"\u2506",rightT:"\u2506",cross:"\u253C"},SLOTS=[["\u256D\u2504\u2504\u256E ","\u2570\u2504\u2504\u256F "],[" \u256D\u256E "," \u2570\u256F "],[" \u2576 "," "]],BLANK=" ",ORDER=[2,1,0,-1],Tail=import_react22.memo((props)=>{let theme=useTheme().theme,refs=import_react22.useRef([]),paint=(lit)=>{SLOTS.forEach((slot,i)=>slot.forEach((l,j2)=>{let node=refs.current[i*2+j2];if(node)node.children=[lit===null||lit===i?l:BLANK]}))};return import_react22.useEffect(()=>{if(!props.run){paint(null);return}let f=0;paint(ORDER[0]);let t2=setInterval(()=>{f=(f+1)%ORDER.length,paint(ORDER[f])},160);return()=>{clearInterval(t2),paint(null)}},[props.run]),$jsx("box",{flexDirection:"column",children:SLOTS.flatMap((slot,i)=>slot.map((l,j2)=>$jsx("text",{fg:theme.hermAvatar,children:$jsx("span",{ref:(el)=>{refs.current[i*2+j2]=el},children:l})},`${i}-${j2}`)))})});function parts(m2){return m2?.parts.filter((p)=>p.type==="thinking"||p.type==="tool")??[]}function latest(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="assistant")return messages[i];return}function rows(list,detail){return list.reduce((n,p)=>n+(p.type==="thinking"?Math.ceil(p.content.length/80)||1:p.type==="tool"?cost(p,detail):1),0)}var ThoughtCloud=import_react22.memo((props)=>{let{theme,syntaxStyle}=useTheme(),detail=usePref("toolDetails")??"expanded",src=props.pick??latest(props.messages),all=parts(src),think=all.filter((p)=>p.type==="thinking"),seen=all.filter((p)=>p.type==="tool").filter((t2)=>visible(t2,detail)),[pane,setPane]=import_react22.useState("reasoning");import_react22.useEffect(()=>{if(pane==="reasoning"&&think.length===0&&seen.length>0)setPane("tools");if(pane==="tools"&&seen.length===0&&think.length>0)setPane("reasoning")},[pane,think.length,seen.length]);let body=pane==="reasoning"?think:seen,manual=import_react22.useRef(!1),want=Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,rows(body,detail)+3)),resize=props.onResize;import_react22.useEffect(()=>{if(!manual.current)resize(want)},[want,resize]);let drag=import_react22.useRef(null),grab=(e)=>{drag.current={y:e.y,h:props.height},manual.current=!0,e.stopPropagation()},move=(e)=>{let d2=drag.current;if(!d2)return;resize(Math.min(CLOUD_MAX,Math.max(CLOUD_MIN,d2.h+(e.y-d2.y))))},drop=()=>{drag.current=null},pill=(id,label,n)=>{let on=pane===id;return $jsx("box",{height:1,marginRight:2,onMouseDown:(e)=>{e.stopPropagation(),setPane(id)},children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.accent:theme.textMuted,children:on?$jsx("strong",{children:label}):label}),n!==null&&n>0?$jsx("span",{fg:theme.textMuted,children:` ${n}`}):null]})})};return $jsxs("box",{height:props.height,flexDirection:"column",position:"relative",marginLeft:1,border:!0,borderColor:theme.hermAvatar,customBorderChars:CLOUD,backgroundColor:theme.backgroundPanel,paddingX:1,children:[$jsxs("box",{height:1,flexShrink:0,flexDirection:"row",children:[pill("reasoning","reasoning",null),pill("tools","tools",seen.length),$jsx("box",{flexGrow:1}),detail!=="expanded"?$jsx("box",{marginRight:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u27E8",detail,"\u27E9"]})}):null,props.onClose?$jsx("box",{width:1,onMouseDown:props.onClose,children:$jsx("text",{fg:theme.textMuted,children:"\xD7"})}):null]}),$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:body.map((p,i)=>p.type==="thinking"?$jsx("box",{minHeight:1,width:"100%",flexShrink:0,children:$jsx("markdown",{content:p.content,fg:theme.markdownText,syntaxStyle})},p.key??`th-${i}`):$jsx("box",{width:"100%",flexShrink:0,children:$jsx(Tool,{branch:i===body.length-1?"last":"mid",tool:p,detail})},p.id||`t-${i}`))})}),$jsx("box",{position:"absolute",left:0,right:0,bottom:0,height:1,onMouseDown:grab,onMouseDrag:move,onMouseUp:drop,onMouseDragEnd:drop})]})});var import_react28=__toESM(require_react_production(),1);var import_react23=__toESM(require_react_production(),1);var def=(chord,desc,scope)=>({chord,desc,scope}),DEFAULTS2={leader:def("ctrl+x","Leader prefix","global"),"app.exit":def("ctrl+c","Quit","global"),"input.clear":def("ctrl+c","Clear input","global"),"app.suspend":def("ctrl+z","Suspend to shell","global"),"app.redraw":def("ctrl+l","Clear & force-repaint terminal","global"),"app.sidebar":def("<leader>b","Toggle sidebar","global"),"palette.open":def("ctrl+k","Command palette","global"),"help.open":def("f1","Keyboard shortcuts","global"),"tab.next":def("alt+right","Next tab","global"),"tab.prev":def("alt+left","Previous tab","global"),"focus.cycle":def("tab","Cycle focus (double-tap \u2192 composer)","global"),"editor.open":def("<leader>e,ctrl+g","Open $EDITOR on prompt","global"),"reply.copy":def("<leader>y,ctrl+y","Copy last assistant reply","global"),"clipboard.attach":def("ctrl+v","Attach clipboard image","global"),"queue.flush":def("<leader>u","Interrupt and send queued now","global"),"session.interrupt":def("escape","Interrupt (double-tap while streaming)","global"),"session.new":def("<leader>n","New session","global"),"session.redo":def("<leader>r","Redo last undo","global"),"session.compress":def("<leader>c","Compress context","global"),"session.steer":def("<leader>s","Steer active turn","global"),"input.stash":def("<leader>p","Stash prompt draft","global"),"session.timeline":def("<leader>g","Session timeline","global"),"theme.pick":def("<leader>t","Switch theme","global"),"model.pick":def("<leader>m","Switch model","global"),"status.open":def("<leader>i","Show status","global"),"list.up":def("up","Move selection up","list"),"list.down":def("down","Move selection down","list"),"list.pageUp":def("pageup","Page up","list"),"list.pageDown":def("pagedown","Page down","list"),"list.home":def("home","First item","list"),"list.end":def("end","Last item","list"),"list.activate":def("return","Activate / open","list"),"list.delete":def("d,delete","Delete item","list"),"list.refresh":def("r","Reload","list"),"list.new":def("n","Create","list"),"list.search":def("/","Filter","list"),"list.toggle":def("space","Toggle item","list"),"dialog.accept":def("return","Accept","dialog"),"dialog.cancel":def("escape","Cancel / close","dialog"),"dialog.confirm":def("y","Yes","dialog"),"dialog.deny":def("n","No","dialog"),"dialog.copy":def("c","Copy body","dialog"),"input.submit":def("return","Send","composer"),"input.newline":def("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline","composer"),"sessions.rename":def("ctrl+r","Retitle session","sessions"),"sessions.prev":def("left","Previous source filter","sessions"),"sessions.next":def("right","Next source filter","sessions"),"agents.kill":def("k","Kill subagent","agents"),"agents.history":def("h","Spawn history","agents"),"agents.install":def("i","Install distribution","agents"),"config.save":def("ctrl+s","Write config","config"),"config.mode":def("m","Toggle form \u2194 YAML","config"),"eikon.save":def("ctrl+s","Save eikon","eikon")};var TAB_SCOPES=new Set(["sessions","cron","env","agents","skills","config","eikon"]);function scopesOverlap(a,b2){if(a===b2)return!0;if(a==="global"||b2==="global")return!0;if(a==="list")return TAB_SCOPES.has(b2);if(b2==="list")return TAB_SCOPES.has(a);return!1}var ALIAS={esc:"escape",enter:"return",del:"delete",ins:"insert",space:"space"," ":"space"};function parse2(spec2){if(!spec2||spec2==="none")return[];return spec2.split(",").map(one)}function one(combo){let c={name:"",ctrl:!1,meta:!1,shift:!1,super:!1,leader:!1};for(let raw of combo.replace(/<leader>/g,"leader+").toLowerCase().split("+")){let p=raw.trim();if(!p)continue;if(p==="ctrl")c.ctrl=!0;else if(p==="alt"||p==="meta"||p==="option")c.meta=!0;else if(p==="shift")c.shift=!0;else if(p==="super"||p==="cmd")c.super=!0;else if(p==="leader")c.leader=!0;else c.name=ALIAS[p]??p}return c}function from(key,leader=!1){return{name:key.name===" "?"space":key.name,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super??!1,leader}}function eq(a,b2){return a.name===b2.name&&a.ctrl===b2.ctrl&&a.meta===b2.meta&&a.shift===b2.shift&&a.super===b2.super&&a.leader===b2.leader}function match(list,key,leader=!1){if(list.length===0)return!1;let k2=from(key,leader);return list.some((c)=>eq(c,k2))}function print(list,lead2){let c=list[0];if(!c)return"";let mods=[];if(c.ctrl)mods.push("Ctrl");if(c.meta)mods.push("Alt");if(c.super)mods.push("Super");if(c.shift)mods.push("Shift");let name=LABEL[c.name]??cap2(c.name),body=[...mods,name].join("+");if(!c.leader)return body;return lead2?`${lead2} ${body}`:`<leader> ${body}`}var LABEL={return:"Enter",escape:"Esc",space:"Space",delete:"Del",backspace:"\u232B",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",pageup:"PgUp",pagedown:"PgDn",home:"Home",end:"End",tab:"Tab"};function cap2(s){return s.length===1?s.toUpperCase():s.charAt(0).toUpperCase()+s.slice(1)}function toBindings(list,action){return list.map((c)=>({name:c.name,ctrl:c.ctrl||void 0,meta:c.meta||void 0,shift:c.shift||void 0,super:c.super||void 0,action}))}function key(c){return`${c.leader?"L":""}${c.ctrl?"C":""}${c.meta?"M":""}${c.shift?"S":""}${c.super?"W":""}-${c.name}`}var LEADER_MS=2000,Ctx2=import_react23.createContext(null),NO_OVERRIDES=Object.freeze({}),KeysProvider=({children,overrides:fixedOverrides})=>{let renderer=useRenderer(),prefOverrides=usePref("keys"),overrides=fixedOverrides??prefOverrides??NO_OVERRIDES,table=import_react23.useMemo(()=>{let t2=new Map;for(let id of Object.keys(DEFAULTS2))t2.set(id,parse2(overrides[id]??DEFAULTS2[id].chord));return t2},[overrides]),lead2=table.get("leader"),leadLabel=print(lead2),armed=import_react23.useRef(!1),stolen=import_react23.useRef(null),timer2=import_react23.useRef(null),[,bump]=import_react23.useState(0),disarm=import_react23.useCallback(()=>{if(!armed.current)return;if(armed.current=!1,timer2.current)clearTimeout(timer2.current),timer2.current=null;let f=stolen.current;if(stolen.current=null,f&&!f.isDestroyed&&!renderer.currentFocusedRenderable)f.focus();bump((n)=>n+1)},[renderer]),arm=import_react23.useCallback(()=>{if(armed.current=!0,stolen.current=renderer.currentFocusedRenderable??null,stolen.current?.blur(),timer2.current)clearTimeout(timer2.current);timer2.current=setTimeout(disarm,LEADER_MS),bump((n)=>n+1)},[renderer,disarm]);useKeyboard((key2)=>{if(!armed.current&&match(lead2,key2)){arm(),key2.stopPropagation();return}if(armed.current)queueMicrotask(disarm)});let value=import_react23.useMemo(()=>({get leader(){return armed.current},match:(id,key2)=>match(table.get(id)??[],key2,armed.current),print:(id)=>print(table.get(id)??[],leadLabel),chord:(id)=>table.get(id)??[],all:(scope)=>Object.keys(DEFAULTS2).filter((id)=>DEFAULTS2[id].scope===scope).map((id)=>({id,desc:DEFAULTS2[id].desc,scope,chord:table.get(id)??[]})),table}),[table,leadLabel]);return $jsx(Ctx2.Provider,{value,children})},useKeys=makeUse(Ctx2,"useKeys");var import_react25=__toESM(require_react_production(),1);function handleListKey(keys,key2,o){let move=(next)=>{o.setSel((p)=>{let n=Math.max(0,Math.min(o.count-1,next(p)));return o.scrollTo?.(n),n})},pg=o.page??10;if(keys.match("list.up",key2))return move((p)=>p-1),!0;if(keys.match("list.down",key2))return move((p)=>p+1),!0;if(keys.match("list.pageUp",key2))return move((p)=>p-pg),!0;if(keys.match("list.pageDown",key2))return move((p)=>p+pg),!0;if(keys.match("list.home",key2))return move(()=>0),!0;if(keys.match("list.end",key2))return move(()=>o.count-1),!0;if(o.onActivate&&keys.match("list.activate",key2))return o.onActivate(),!0;if(o.onDelete&&keys.match("list.delete",key2))return o.onDelete(),!0;if(o.onRefresh&&keys.match("list.refresh",key2))return o.onRefresh(),!0;if(o.onNew&&keys.match("list.new",key2))return o.onNew(),!0;if(o.onToggle&&keys.match("list.toggle",key2))return o.onToggle(),!0;if(o.onSearch&&keys.match("list.search",key2))return o.onSearch(),!0;return!1}function useListKeys(o){let keys=useKeys();return useKeyboard((key2)=>{if(!(typeof o.active==="function"?o.active():o.active))return;if(handleListKey(keys,key2,o))return;o.also?.(key2,keys)}),keys}function useFollow(prefix,key2){let ref=import_react25.useRef(null),id=(i)=>`${prefix}-row-${key2?.(i)??i}`;return{ref,id,opts:{scrollTo:(n)=>ref.current?.scrollChildIntoView(id(n)),get page(){return Math.max(1,(ref.current?.viewport.height??10)-1)}}}}function conflicts(table){let buckets=new Map;for(let[id,chords]of table)for(let c of chords){let k2=key(c),b2=buckets.get(k2);if(b2)b2.push([id,c]);else buckets.set(k2,[[id,c]])}let out=[];for(let bucket of buckets.values()){if(bucket.length<2)continue;for(let i=0;i<bucket.length;i++)for(let j2=i+1;j2<bucket.length;j2++){let[a,c]=bucket[i],[b2]=bucket[j2];if(scopesOverlap(DEFAULTS2[a].scope,DEFAULTS2[b2].scope))out.push({chord:c,a,b:b2})}}return out}function conflictsWith(table,id){let mine=new Set((table.get(id)??[]).map(key));if(mine.size===0)return[];let scope=DEFAULTS2[id].scope,out=[];for(let[other,chords]of table){if(other===id)continue;if(!scopesOverlap(scope,DEFAULTS2[other].scope))continue;if(chords.some((c)=>mine.has(key(c))))out.push(other)}return out}var import_react27=__toESM(require_react_production(),1);var TabStrip=import_react27.memo(({tabs,active,onChange,hint})=>{let theme=useTheme().theme;return $jsxs("box",{width:"100%",flexDirection:"row",height:1,overflow:"hidden",children:[tabs.map((name,i)=>$jsx("box",{onMouseDown:()=>onChange(i),paddingX:2,marginRight:1,flexShrink:0,backgroundColor:i===active?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===active?theme.primary:theme.textMuted,children:$jsx("strong",{children:name})})},i)),$jsx("box",{flexGrow:1,minWidth:0}),hint?$jsx("box",{paddingX:1,flexShrink:1,minWidth:0,overflow:"hidden",children:$jsx("text",{fg:theme.borderSubtle,children:hint})}):null]})});var TabBar=import_react28.memo(({tabs,activeTab,onTabChange})=>{let keys=useKeys(),hint=`${keys.print("tab.prev")}/${keys.print("tab.next")} or ${keys.print("leader")} N`;return $jsx(TabStrip,{tabs:tabs.map((t2)=>t2.name),active:activeTab,onChange:onTabChange,hint})});var import_react32=__toESM(require_react_production(),1);var import_react29=__toESM(require_react_production(),1);var default_default=`{"type":"header","asset":{"version":"2.0","minVersion":"2.0","width":48,"height":24,"mediaType":"application/vnd.eikon.stream+jsonl"},"name":"nous-girl"}
|
|
3678
3678
|
{"type":"clip","name":"idle","fps":16,"frameCount":64,"loopFrom":0}
|
|
3679
3679
|
{"type":"frame","clip":"idle","index":0,"rows":["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28C0\u28C0\u28E0\u28E4\u28E4\u28C0\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28C0\u28E4\u28E4\u28EC\u28E5\u28C4\u28C0\u2800\u2809\u2819\u283B\u28FF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E4\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E4\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E6\u2840\u2800\u2808\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28E4\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u287F\u28A6\u2840\u2800\u2808\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u2857\u2804\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2870\u28FB\u28FF\u28FF\u28FF\u288F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2819\u280F\u2800\u2800\u28EE\u2873\u2800\u2800\u2808\u28BF\u28BF\u283B\u283F\u284F\u2801\u2801\u28F8\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u280C\u2808\u2809\u28BA\u283B\u2883\u280A\u2819\u281B\u28A0\u2840\u2880\u2819\u2801\u2801\u2800\u2858\u28F6\u28F7\u28FF\u28F7\u28FE\u2800\u2800\u2808\u28F6\u28C6\u28F3\u28F6\u28EE\u2894\u28FF\u28FF\u2846\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u287C\u28F4\u28B6\u28E4\u28F6\u28FE\u28FC\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FE\u28F6\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2847\u28C0\u28E0\u28F8\u28FF\u28F7\u28FB\u28FF\u28FF\u28FF\u28FF\u28F7\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28AF\u28FF\u28DA\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u28D7\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u2858\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2827\u283B\u281F\u28FB\u281F\u2853\u2808\u281B\u281B\u281B\u281B\u281B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u283B\u28FF\u287F\u28FF\u28FF\u28C9\u28C1\u2800\u2800\u2800\u2800\u2838\u28BB\u28FF\u2877\u28A6\u2844\u2800\u2800\u2800\u28B9\u28FF\u28FF\u28FF\u28FF\u289F\u28DB\u287B\u28FF\u28FF\u28FF\u28EF\u28FF\u28FF\u28FF\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2808\u2819\u280A\u28BB\u28CF\u28BF\u2807\u2800\u2800\u2800\u2800\u282C\u283F\u2825\u280A\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287C\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28F8\u28EF\u280A\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u2847\u2820\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u28FF\u28FF\u28FF\u28FF\u2847\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28C7\u2830\u28C4\u28C4\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28FF\u28FF\u28FF\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B0\u28FF\u28FF\u2846\u2823\u2804\u2808\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u28FF\u28FF\u28FF\u283B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FC\u28FF\u28FF\u28B9\u28FF\u28C7\u2800\u2800\u2800\u2800","\u2800\u2800\u28A0\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u284F\u2888\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2804\u28FF\u28FF\u2840\u2800\u2800\u2800","\u2800\u2800\u28DF\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28E6\u28C0\u28C0\u28C0\u28C0\u28E0\u28C4\u2840\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u287E\u281F\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2801\u28F9\u28FF\u2847\u2810\u2844\u2800","\u2800\u2880\u28FF\u28E6\u28C0\u28E0\u28FC\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C4\u2800\u28F8\u28FF\u28FF\u28EF\u2840\u28C0\u28FC\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2880\u28FF\u28FF\u2847\u2800\u28F7\u2800","\u2800\u2818\u28DC\u283F\u28FF\u28FF\u283F\u280B\u28F1\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u280B\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E3\u28FE\u28FF\u28FF\u2847\u28A0\u28FF\u2800","\u2800\u2800\u2819\u283F\u28F6\u28E4\u28F6\u28FE\u28FF\u28FF\u288B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u281B\u288B\u2860\u2886\u2800\u2819\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28A0\u28FF\u280F\u2800","\u2800\u2800\u2800\u2800\u2800\u2809\u28AF\u28C9\u28C9\u28E1\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2840\u288B\u281D\u2803\u28C0\u28F4\u281F\u282B\u289B\u28ED\u287F\u281A\u280B\u2809\u2801\u2812\u282B\u28DD\u283B\u28FF\u28FF\u28FF\u289F\u28F5\u287F\u280B\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u281B\u283F\u283F\u281B\u2881\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2876\u281F\u2809\u2800\u2880\u28F4\u285F\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2833\u28DC\u28BF\u287F\u281F\u280B\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u283F\u28FF\u28AF\u287E\u280B\u2800\u2800\u2880\u2854\u2800\u287E\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u282E\u2805\u2800\u2800\u2800\u2800\u2800\u2800"]}
|
|
3680
3680
|
{"type":"frame","clip":"idle","index":1,"rows":["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E0\u28E0\u28C0\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E4\u28E4\u28E4\u28E5\u28E4\u28C0\u2800\u2809\u2809\u283B\u28BF\u28FF\u28FF\u28FF\u28F7\u28F6\u28E4\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28E4\u28F6\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F6\u28C4\u2800\u2800\u2819\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28DF\u287F\u28B7\u2840\u2800\u2808\u28BB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2880\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2860\u28EB\u287F\u28FF\u28FF\u289F\u28FE\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u280E\u281F\u2800\u2800\u28B4\u287B\u2804\u2800\u2800\u28BB\u28FF\u283F\u28BF\u28FF\u2803\u2809\u28A0\u28E4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2814\u2804\u2800\u2819\u2833\u280B\u280E\u2809\u281A\u2881\u28C4\u28C0\u28B8\u2809\u2801\u2800\u2848\u28B6\u28FE\u28FF\u28F7\u28FE\u2840\u2800\u2800\u28B6\u28E6\u2874\u28E6\u28F6\u28C2\u28E6\u28BF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u28F8\u28F5\u28E6\u28E7\u28F6\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FB\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C7\u2880\u28C0\u2878\u28FF\u28FF\u28FB\u28FF\u28F7\u28BE\u28FF\u28FF\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28A0\u28F7\u28FF\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CC\u28FF\u28F0\u28BF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BF\u28FF\u28FF\u28FF\u28FF\u285C\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u285F\u28FF\u28FF\u28FF\u28FF\u28FF\u2843\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2818\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u2807\u2819\u281B\u287B\u289F\u28CB\u2809\u281B\u281B\u281B\u281B\u281B\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28F7\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2819\u28BF\u28DF\u28BF\u28FF\u28C1\u28D0\u2800\u2800\u2800\u2800\u2818\u28BB\u28FF\u2877\u28A6\u2844\u2800\u2800\u2800\u28F8\u28FF\u28FF\u28FF\u28FF\u281F\u281B\u283B\u28FF\u28FF\u28FF\u28EF\u28FF\u28FF\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u2803\u28B9\u28CF\u28BB\u2807\u2800\u2800\u2800\u2800\u2828\u283D\u2825\u280A\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F9\u28FF\u28FF\u28FF\u28FF\u28C7\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28CF\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28BF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u2807\u2820\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u28FF\u28FF\u28FF\u28FF\u2847\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28C7\u2838\u28C4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28CF\u28FF\u28FF\u28FF\u28FF\u28FF\u2800\u2800\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B0\u28FF\u28FF\u2846\u282B\u2800\u2808\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28FF\u28FF\u28FF\u28FF\u28B9\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28BB\u28FF\u2847\u2800\u2800\u2800\u2800","\u2800\u2800\u2860\u2800\u2800\u2800\u2800\u28F8\u28FF\u28FF\u28FF\u2844\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28FC\u28FF\u28FF\u28FF\u2803\u2898\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2808\u28FF\u28FF\u2800\u2800\u2800\u2800","\u2800\u28A0\u28E7\u2800\u2800\u2800\u2880\u28FF\u28FF\u28FF\u28FF\u28FF\u28E6\u28C0\u28C0\u28C0\u28C0\u28E0\u28C4\u2840\u2800\u2800\u28FF\u28FF\u28FF\u28EF\u2876\u281F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u2801\u28B9\u28FF\u2847\u28A0\u2800\u2800","\u2800\u2808\u28FF\u28F6\u28E4\u28E4\u28FE\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28C4\u2800\u28FF\u28FF\u28FF\u28CF\u2800\u28E0\u28FE\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u2880\u28FF\u28FF\u2847\u2800\u28E7\u2800","\u2800\u2818\u28CC\u287B\u283F\u283F\u281F\u288B\u28FC\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287E\u281B\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E3\u28FE\u28FF\u28FF\u2847\u28B0\u28FF\u2800","\u2800\u2800\u2818\u283B\u28F7\u28F6\u28FE\u28FF\u28FF\u287F\u28B3\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u281B\u288B\u2860\u2886\u2808\u283B\u28BF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u287F\u28A0\u28FF\u2807\u2800","\u2800\u2800\u2800\u2800\u2800\u2808\u28EF\u28C9\u28C1\u28F4\u28FF\u287F\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28E7\u2840\u288B\u281D\u2803\u28C0\u28F4\u281F\u283B\u289B\u28ED\u287F\u281A\u280B\u2809\u2801\u2812\u282B\u28D9\u283B\u28FF\u28FF\u28FF\u285F\u28F1\u28FF\u280B\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u281B\u281B\u281B\u280B\u28F0\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28FF\u28F7\u28E4\u2876\u281F\u2809\u2800\u2880\u28F4\u281F\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2833\u28DC\u28BF\u28FF\u283F\u280B\u2801\u2800\u2800\u2800","\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28F0\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u28FF\u28AF\u287E\u280B\u2800\u2800\u2880\u2854\u2880\u287E\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u283A\u2805\u2800\u2800\u2800\u2800\u2800\u2800"]}
|
|
@@ -4085,22 +4085,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
4085
4085
|
`));return e}function lintManifest(path6,raw){let man=JSON.parse(raw),dir=dirname4(path6),errs=[];if("license"in man||"provenance"in man)errs.push("manifest must not contain license or provenance");if(!NAME_RE.test(man.name))errs.push(`name "${man.name}" must match ${NAME_RE}`);if(basename4(dir)!==man.name)errs.push(`name "${man.name}" \u2260 folder "${basename4(dir)}"`);if(man.source&&!existsSync7(join6(dir,man.source)))errs.push(`source: ${man.source} missing`);if(!man.states||typeof man.states!=="object")errs.push("states: object required");else for(let[st,v2]of Object.entries(man.states))if(!STATES.includes(st))errs.push(`states.${st}: unknown state`);else if(!v2?.file)errs.push(`states.${st}.file required`);else if(!existsSync7(join6(dir,v2.file)))errs.push(`states.${st}.file: ${v2.file} missing`);if(errs.length)throw Error(`${path6}:
|
|
4086
4086
|
${errs.join(`
|
|
4087
4087
|
`)}`);return man}import{existsSync as existsSync8,mkdirSync as mkdirSync3,readFileSync as readFileSync3,writeFileSync as writeFileSync4,copyFileSync,renameSync as renameSync2,rmSync,statSync,readdirSync as readdirSync2,lstatSync}from"fs";import{join as join7,extname as extname2,basename as basename5,dirname as dirname5}from"path";import{mkdtempSync}from"fs";import{tmpdir}from"os";import{createHash as createHash2}from"crypto";var NAME_RE2=/^[a-z0-9][a-z0-9-]{1,63}$/,SAFE_PATH_RE=/^[a-zA-Z0-9._/-]+$/,problem=(path6,message)=>({code:"manifest",path:path6,message:`${path6}: ${message}`}),isObj2=(value)=>!!value&&typeof value==="object"&&!Array.isArray(value),isSafeText=(value)=>!/[<>\u0000-\u001f]/.test(value),isSha256=(value)=>typeof value==="string"&&/^sha256:[A-Za-z0-9._~+/=-]+$/.test(value),isEncoding=(value)=>typeof value==="string"&&RUNTIME_ENCODINGS.includes(value),isRuntimePath=(path6)=>path6.endsWith(LAUNCH_STREAM_EXTENSION)||/^blobs\/sha256\/[A-Fa-f0-9]{16,}(?:\.eikon)?$/.test(path6),STALE_DESCRIPTOR_ROLES=new Set(["stream","source"]);function isSafeRelativePath(path6){if(!path6||path6.startsWith("/")||path6.startsWith("./")||path6.includes("../")||path6==="..")return!1;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(path6))return!1;if(!SAFE_PATH_RE.test(path6))return!1;return!path6.split("/").includes("..")}function supportsLaunch(range){let parts2=[...range.matchAll(/(>=|>|<=|<|==|=)?\s*(\d+)(?:\.\d+)?/g)];if(!parts2.length)return!0;return parts2.every(([,op="=",raw])=>{let n=Number(raw);if(op===">=")return LAUNCH_MAJOR_VERSION>=n;if(op===">")return LAUNCH_MAJOR_VERSION>n;if(op==="<=")return LAUNCH_MAJOR_VERSION<=n;if(op==="<")return LAUNCH_MAJOR_VERSION<n;return LAUNCH_MAJOR_VERSION===n})}function validateDescriptor(file,index,opts,errs){let base=`files.${index}`;if(!file||typeof file!=="object"){errs.push(problem(base,"descriptor object required"));return}if(typeof file.path!=="string"||!isSafeRelativePath(file.path))errs.push(problem(`${base}.path`,"safe relative path required"));if(typeof file.role!=="string"||!file.role)errs.push(problem(`${base}.role`,"role required"));else if(STALE_DESCRIPTOR_ROLES.has(file.role))errs.push(problem(`${base}.role`,`stale descriptor role "${file.role}"; use final runtime/source.base/source.clip roles`));if(typeof file.mediaType!=="string"||!file.mediaType)errs.push(problem(`${base}.mediaType`,"mediaType required"));if(file.role==="runtime"){if(!isRuntimePath(file.path))errs.push(problem(`${base}.path`,`runtime descriptor must point at launch ${LAUNCH_STREAM_EXTENSION} stream or content-addressed blob`));if(file.mediaType!==LAUNCH_MEDIA_TYPE)errs.push(problem(`${base}.mediaType`,`runtime descriptor must use ${LAUNCH_MEDIA_TYPE}`));if(file.encoding!=null&&!isEncoding(file.encoding))errs.push(problem(`${base}.encoding`,"runtime encoding must be identity or gzip"));let enc=file.encoding??"identity";if(file.decodedSize!=null&&(typeof file.decodedSize!=="number"||!Number.isFinite(file.decodedSize)||file.decodedSize<0))errs.push(problem(`${base}.decodedSize`,"non-negative number required"));if(file.decodedDigest!=null&&!isSha256(file.decodedDigest))errs.push(problem(`${base}.decodedDigest`,"sha256 digest required"));if(opts.registry&&enc==="gzip"){let missing=[];if(typeof file.size!=="number"||!Number.isFinite(file.size)||file.size<0)missing.push("size");if(!isSha256(file.digest))missing.push("digest");if(typeof file.decodedSize!=="number"||!Number.isFinite(file.decodedSize)||file.decodedSize<0)missing.push("decodedSize");if(!isSha256(file.decodedDigest))missing.push("decodedDigest");if(missing.length)errs.push(problem(base,`${missing.join(" ")} required for gzip registry runtime descriptors`))}}else if(file.encoding!=null||file.decodedSize!=null||file.decodedDigest!=null)errs.push(problem(base,"runtime encoding metadata is only valid on runtime descriptors"));if(opts.registry){let missing=[];if(typeof file.size!=="number"||!Number.isFinite(file.size)||file.size<0)missing.push("size");if(!isSha256(file.digest))missing.push("digest");if(missing.length)errs.push(problem(base,`${missing.join(" ")} required for registry descriptors`))}}function validatePackageManifest(value,opts={}){let errs=[];if(!isObj2(value))throw new EikonValidationError([problem("manifest","object required")]);let raw=value,man=value;if(man.kind!==PACKAGE_KIND)errs.push(problem("kind",`must be ${PACKAGE_KIND}`));if(man.schemaVersion!==PACKAGE_SCHEMA_VERSION)errs.push(problem("schemaVersion",`must be ${PACKAGE_SCHEMA_VERSION}`));if(!NAME_RE2.test(String(man.name??"")))errs.push(problem("name","safe package name required"));if(!man.id||typeof man.id!=="string"||!isSafeText(man.id))errs.push(problem("id","safe id required"));if(opts.registry&&(typeof man.version!=="string"||!man.version))errs.push(problem("version","version required for registry packages"));if(!isObj2(man.compatibility)||typeof man.compatibility.eikon!=="string"||!supportsLaunch(man.compatibility.eikon))errs.push(problem("compatibility.eikon","must support launch major version 1"));if(!isObj2(man.entrypoints)||typeof man.entrypoints.default!=="string"||!isSafeRelativePath(man.entrypoints.default))errs.push(problem("entrypoints.default","safe relative path required"));if(typeof man.entrypoints?.default==="string"&&!isRuntimePath(man.entrypoints.default))errs.push(problem("entrypoints.default",`must point at launch ${LAUNCH_STREAM_EXTENSION} runtime stream or content-addressed blob`));for(let[key2,path6]of Object.entries(man.entrypoints??{}))if(typeof path6!=="string"||!isSafeRelativePath(path6))errs.push(problem(`entrypoints.${key2}`,"safe relative path required"));if("signals"in raw)errs.push(problem("signals","runtime signal mappings belong in the .eikon header"));if(opts.registry&&!Array.isArray(man.files))errs.push(problem("files","files descriptors required for registry packages"));for(let[index,file]of(man.files??[]).entries())validateDescriptor(file,index,opts,errs);let runtime=(man.files??[]).find((file)=>file.role==="runtime"&&file.path===man.entrypoints.default);if(opts.registry&&!runtime)errs.push(problem("files","runtime descriptor for entrypoints.default required"));if(man.source?.base&&!isSafeRelativePath(man.source.base))errs.push(problem("source.base","safe relative path required"));for(let[key2,source]of Object.entries(man.source?.states??{}))if(!source||typeof source!=="object"||typeof source.file!=="string"||!isSafeRelativePath(source.file))errs.push(problem(`source.states.${key2}.file`,"safe relative path required"));for(let ext of man.extensions?.required??[])errs.push(problem("extensions.required",`unknown required Eikon extension ${ext}`));if(man.poster&&!isSafeRelativePath(man.poster))errs.push(problem("poster","safe relative path required"));for(let[key2,value2]of Object.entries(man.display??{})){if(typeof value2==="string"&&!isSafeText(value2))errs.push(problem(`display.${key2}`,"unsafe text"));if(Array.isArray(value2)&&value2.some((item)=>typeof item!=="string"||!isSafeText(item)))errs.push(problem(`display.${key2}`,"unsafe text"))}for(let trigger of man.triggers??[])if(!trigger||typeof trigger.signal!=="string"||typeof trigger.when!=="string")errs.push(problem("triggers","signal and when required"));if(errs.length)throw new EikonValidationError(errs);return man}function buffer(bytes){return bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)}async function sha256Bytes2(bytes){let out=await globalThis.crypto.subtle.digest("SHA-256",buffer(bytes));return`sha256:${[...new Uint8Array(out)].map((n)=>n.toString(16).padStart(2,"0")).join("")}`}async function assertDigest2(bytes,expected,label){if(expected&&await sha256Bytes2(bytes)!==expected)runtimeError(`runtime ${label} digest mismatch`)}async function decodeRuntimeBytes2(bytes,opts={}){assertBytes(bytes,opts),await assertDigest2(bytes,opts.descriptor?.digest,"stored");let decoded=runtimeEncoding(bytes,opts.descriptor)==="gzip"?await gunzip2(bytes,opts.maxDecodedBytes??DEFAULT_RUNTIME_MAX_DECODED_BYTES):bytes;return assertDecoded(decoded,opts),await assertDigest2(decoded,opts.descriptor?.decodedDigest,"decoded"),utf8(decoded)}async function gunzip2(bytes,max){let ctor=globalThis.DecompressionStream;if(!ctor)runtimeError("runtime gzip decode unsupported in this browser");try{let source=new ReadableStream({start(ctrl){ctrl.enqueue(new Uint8Array(buffer(bytes))),ctrl.close()}}),gzip=new ctor("gzip"),reader=source.pipeThrough(gzip).getReader(),chunks=[],size=0;for(;;){let item=await reader.read();if(item.done)break;if(size+=item.value.length,size>max)await reader.cancel(),runtimeError(`runtime decoded byte limit exceeded: ${size} > ${max}`);chunks.push(item.value)}let out=new Uint8Array(size),at=0;for(let chunk of chunks)out.set(chunk,at),at+=chunk.length;return out}catch(err){if(err instanceof Error&&err.message.includes("runtime decoded byte limit"))throw err;runtimeError(`runtime gzip decode failed: ${err instanceof Error?err.message:String(err)}`)}}var PRIVATE_HOSTS=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]);function privateIpv4(a,b2){if(a===10||a===127)return!0;if(a===169&&b2===254)return!0;if(a===192&&b2===168)return!0;return a===172&&b2>=16&&b2<=31}function mappedIpv4Private(host){let dotted=host.match(/^::ffff:(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(dotted)return privateIpv4(Number(dotted[1]),Number(dotted[2]));let hex=host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!hex)return!1;let n=Number.parseInt(hex[1],16)*65536+Number.parseInt(hex[2],16);return privateIpv4(Math.floor(n/16777216),Math.floor(n/65536)&255)}function privateHost(host){let h2=host.toLowerCase().replace(/^\[|\]$/g,"");if(PRIVATE_HOSTS.has(h2))return!0;if(h2.endsWith(".localhost"))return!0;let ip=h2.match(/^(\d+)\.(\d+)\./);if(ip&&privateIpv4(Number(ip[1]),Number(ip[2])))return!0;if(h2.startsWith("fe80:"))return!0;if(/^f[cd][0-9a-f]{2}:/.test(h2))return!0;return mappedIpv4Private(h2)}function pathParts(raw){let path6=raw.split(/[?#]/,1)[0]??raw,decoded=(()=>{try{return decodeURIComponent(path6)}catch{return path6}})();return[path6,decoded]}function pathEscape(raw){return pathParts(raw).some((value)=>/%5c/i.test(value)||value.split(/[\\/]/).some((part)=>part===".."))}var DEFAULT_PUBLIC_CATALOG=DEFAULT_CATALOG,NAME_RE3=/^[a-z0-9][a-z0-9-]{1,63}$/,text2=(value)=>typeof value==="string"&&!/[<>\u0000-\u001f]/.test(value),isObj3=(value)=>!!value&&typeof value==="object"&&!Array.isArray(value),problem2=(path6,message)=>({code:"catalog",path:path6,message:`${path6}: ${message}`}),digestRe=/^sha256:[A-Za-z0-9._~+/=-]+$/,encodings=new Set(["identity","gzip"]),trimSlash=(s)=>s.replace(/\/$/,""),slash=(s)=>s.replace(/\/?$/,"/"),clean=(value)=>typeof value==="string"?value.replace(/[\u0000-\u001f\u007f-\u009f]/g,""):void 0,cleanTextBlock=(value)=>typeof value==="string"?value.replace(/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\u009f]/g,""):void 0;var blobDigest=(value)=>{let m2=new URL(value).pathname.match(/\/blobs\/sha256\/([A-Fa-f0-9]{64})(?:\.eikon)?$/);return m2?`sha256:${m2[1].toLowerCase()}`:void 0},isRuntimeUrl=(value)=>value.endsWith(".eikon")||/\/blobs\/sha256\/[A-Fa-f0-9]{16,}(?:\.eikon)?$/.test(new URL(value).pathname),goodSize=(value)=>typeof value==="number"&&Number.isFinite(value)&&value>=0;async function sha256(bytes){let copy=new Uint8Array(bytes),hash=await crypto.subtle.digest("SHA-256",copy.buffer);return`sha256:${[...new Uint8Array(hash)].map((byte)=>byte.toString(16).padStart(2,"0")).join("")}`}function publicCatalogUrl(raw=DEFAULT_PUBLIC_CATALOG,base,opts={}){let out;try{out=new URL(raw,base)}catch{throw Error("public catalog URL is invalid")}if(pathEscape(raw))throw Error(`public catalog URL path escape: ${out.origin}${out.pathname}`);if(opts.allowPrivate&&out.protocol==="file:")return out.href;if(out.protocol!=="https:"&&out.protocol!=="http:")throw Error(`public catalog URL must use http(s): ${out.href}`);if(out.username||out.password)throw Error(`public catalog URL cannot include credentials: ${out.protocol}//[redacted]@${out.host}${out.pathname}`);for(let key2 of out.searchParams.keys())if(/token|secret|key|credential|password/i.test(key2))throw Error(`public catalog URL cannot include credentials: ${out.origin}${out.pathname}`);if(!opts.allowPrivate&&privateHost(out.hostname))throw Error(`public catalog URL cannot use private host: ${out.hostname}`);if(out.protocol==="http:"&&!privateHost(out.hostname))throw Error(`public catalog URL must use https: ${out.href}`);if(out.pathname.split("/").some((p)=>p===".."))throw Error(`public catalog URL path escape: ${out.href}`);return out.href}function url(value,base){try{return publicCatalogUrl(value,base,{allowPrivate:!0})}catch{throw new EikonValidationError([problem2("packageUrl","http(s) URL required")])}}function joinUrl(base,path6){return new URL(path6,base.endsWith("/")?base:`${base}/`).toString()}function relativeUrl(base,path6){if(!path6)return;if(/^https?:\/\//.test(path6))return url(path6);if(!isSafeRelativePath(path6))throw new EikonValidationError([problem2("path","safe relative path required")]);return joinUrl(base,path6)}function assetUrl(raw,base,fallback,opts={}){let input=raw||fallback,out=publicCatalogUrl(input,input.includes("://")?void 0:slash(base),opts),root=new URL(slash(base)),parsed=new URL(out);if(parsed.host!==root.host)throw Error(`public catalog URL host must match catalog host: ${out}`);if(!parsed.pathname.startsWith(root.pathname))throw Error(`public catalog URL path escape: ${out}`);return out}function runtimeDescriptor(man){return man.files?.find((file)=>file.role==="runtime"&&file.path===runtimePath(man))}function digestFor(man,path6){return man.files?.find((file)=>file.path===path6)?.digest}function runtimePath(man){return man.entrypoints.default}function catalogEntry(entry,base=DEFAULT_PUBLIC_CATALOG,opts={}){return publicFromEntry(fromLegacy(entry,base,opts),entry)}function publicFromEntry(entry,raw=entry){return{...entry,trust:entry.trust??{},poster:entry.poster??"",w:0,h:0,width:0,height:0,identityKey:entry.sourceKey||entry.id,raw}}function runtimeDesc(entry){let trust=entry.trust,digest=trust?.runtimeDigest??blobDigest(entry.runtimeUrl);if(!digest&&!trust?.runtimeSize&&!trust?.runtimeEncoding&&!trust?.runtimeDecodedSize&&!trust?.runtimeDecodedDigest)return;return{digest,size:trust?.runtimeSize,encoding:trust?.runtimeEncoding,decodedSize:trust?.runtimeDecodedSize,decodedDigest:trust?.runtimeDecodedDigest}}function assertArtifactHeaders(res,entry){let enc=res.headers.get("content-encoding");if(enc&&enc.toLowerCase()!=="identity"&&(entry.trust?.runtimeDigest||blobDigest(entry.runtimeUrl)))throw Error(`catalog: runtime artifact must be served without Content-Encoding: ${enc}`)}async function loadRuntimeArtifact(entry,fetcher=fetch,opts={}){if(publicCatalogUrl(entry.runtimeUrl,void 0,{allowPrivate:opts.allowPrivate}),publicCatalogUrl(entry.packageUrl,void 0,{allowPrivate:opts.allowPrivate}),entry.trust?.manifestDigest){let pkg=await fetcher(entry.packageUrl,opts.signal?{signal:opts.signal}:void 0);if(pkg.url)publicCatalogUrl(pkg.url,void 0,{allowPrivate:opts.allowPrivate});if(!pkg.ok)throw Error(`catalog: package HTTP ${pkg.status}`);let body=new Uint8Array(await pkg.arrayBuffer());if(await sha256(body)!==entry.trust.manifestDigest)throw Error("catalog: package manifest digest mismatch")}let out=await fetcher(entry.runtimeUrl,opts.signal?{signal:opts.signal}:void 0);if(out.url)publicCatalogUrl(out.url,void 0,{allowPrivate:opts.allowPrivate});if(!out.ok)throw Error(`catalog: HTTP ${out.status}`);assertArtifactHeaders(out,entry);let bytes=new Uint8Array(await out.arrayBuffer());if(opts.maxBytes!=null&&bytes.length>opts.maxBytes)throw Error("catalog: size limit exceeded");return{bytes,text:await decodeRuntimeBytes2(bytes,{descriptor:runtimeDesc(entry),maxBytes:opts.maxBytes,maxDecodedBytes:opts.maxBytes})}}function fromPackage(input,root,opts={}){let man=validatePackageManifest(input.manifest),packageUrl=url(input.packageUrl,root),base=packageUrl.slice(0,packageUrl.lastIndexOf("/")+1),runtime=runtimePath(man),desc=runtimeDescriptor(man),runtimeUrl=relativeUrl(base,runtime);return validateCatalogEntry({kind:CATALOG_KIND,schemaVersion:CATALOG_SCHEMA_VERSION,id:man.id,version:man.version,sourceKey:input.sourceKey??`registry:${new URL(packageUrl).host}:${man.id}${man.version?`@${man.version}`:""}`,name:man.name,title:man.display?.title,author:man.display?.author,description:man.display?.description,glyph:man.display?.glyph,tags:man.display?.tags,poster:relativeUrl(base,man.poster),runtimeUrl,packageUrl,detailUrl:input.detailUrl?url(input.detailUrl,base):void 0,compatibility:{eikon:man.compatibility.eikon,available:!0},trust:{manifestDigest:input.trust?.manifestDigest??digestFor(man,"manifest.json"),runtimeDigest:input.trust?.runtimeDigest??desc?.digest,runtimeSize:input.trust?.runtimeSize??desc?.size,runtimeEncoding:input.trust?.runtimeEncoding??desc?.encoding,runtimeDecodedSize:input.trust?.runtimeDecodedSize??desc?.decodedSize,runtimeDecodedDigest:input.trust?.runtimeDecodedDigest??desc?.decodedDigest}},opts)}function fromLegacy(input,base,opts={}){if(!NAME_RE3.test(input.name))throw new EikonValidationError([problem2("name","safe catalog name required")]);let source=input.source??`${input.name}/`;if(/^file:|^javascript:|^data:/i.test(source))throw new EikonValidationError([problem2("packageUrl","http(s) URL required")]);if(!/^https?:\/\//.test(source)&&!isSafeRelativePath(source))throw new EikonValidationError([problem2("path","path escape")]);let root=/^https?:\/\//.test(source)?publicCatalogUrl(source,void 0,opts):base?joinUrl(base,source):source,catalogRoot=base?slash(base):root,runtimeUrl=typeof input.runtimeUrl==="string"?assetUrl(input.runtimeUrl,catalogRoot,"",opts):typeof input.runtime_url==="string"?assetUrl(input.runtime_url,catalogRoot,"",opts):joinUrl(root,`${input.name}.eikon`),packageUrl=typeof input.packageUrl==="string"?url(input.packageUrl,catalogRoot):typeof input.package_url==="string"?url(input.package_url,catalogRoot):joinUrl(root,"manifest.json");return validateCatalogEntry({kind:CATALOG_KIND,schemaVersion:CATALOG_SCHEMA_VERSION,id:input.name,version:input.version,sourceKey:/^https?:\/\//.test(root)?root:input.name,name:input.name,title:clean(input.name),author:clean(input.author),glyph:clean(input.glyph),tags:Array.isArray(input.tags)?input.tags.filter(text2):void 0,poster:cleanTextBlock(input.poster),runtimeUrl,packageUrl,detailUrl:typeof input.detailUrl==="string"?url(input.detailUrl,root):typeof input.detail_url==="string"?url(input.detail_url,root):void 0,description:clean(input.description),compatibility:{eikon:">=1 <2",available:!0},trust:{}},opts)}function validateCatalogEntry(entry,opts={}){let errs=[];if(entry.kind!==CATALOG_KIND)errs.push(problem2("kind",`must be ${CATALOG_KIND}`));if(entry.schemaVersion!==CATALOG_SCHEMA_VERSION)errs.push(problem2("schemaVersion",`must be ${CATALOG_SCHEMA_VERSION}`));if(!NAME_RE3.test(entry.name))errs.push(problem2("name","safe catalog name required"));for(let[key2,value]of Object.entries({id:entry.id,sourceKey:entry.sourceKey,title:entry.title,author:entry.author,description:entry.description,glyph:entry.glyph}))if(value!=null&&!text2(value))errs.push(problem2(key2,"unsafe text"));try{publicCatalogUrl(entry.packageUrl,void 0,opts)}catch{errs.push(problem2("packageUrl","safe http(s) URL required"))}try{publicCatalogUrl(entry.runtimeUrl,void 0,opts)}catch{errs.push(problem2("runtimeUrl","safe http(s) URL required"))}if(entry.runtimeUrl&&!isRuntimeUrl(entry.runtimeUrl))errs.push(problem2("runtimeUrl","must point at launch .eikon stream or content-addressed blob"));let trust=entry.trust;if(trust?.manifestDigest!=null&&!digestRe.test(trust.manifestDigest))errs.push(problem2("trust.manifestDigest","sha256 digest required"));if(trust?.runtimeDigest!=null&&!digestRe.test(trust.runtimeDigest))errs.push(problem2("trust.runtimeDigest","sha256 digest required"));if(trust?.runtimeDecodedDigest!=null&&!digestRe.test(trust.runtimeDecodedDigest))errs.push(problem2("trust.runtimeDecodedDigest","sha256 digest required"));if(trust?.runtimeSize!=null&&!goodSize(trust.runtimeSize))errs.push(problem2("trust.runtimeSize","non-negative finite size required"));if(trust?.runtimeDecodedSize!=null&&!goodSize(trust.runtimeDecodedSize))errs.push(problem2("trust.runtimeDecodedSize","non-negative finite size required"));if(trust?.runtimeEncoding!=null&&!encodings.has(trust.runtimeEncoding))errs.push(problem2("trust.runtimeEncoding","unsupported runtime encoding"));if(trust?.runtimeEncoding==="gzip"){if(!trust.runtimeDigest)errs.push(problem2("trust.runtimeDigest","required for gzip runtime"));if(!goodSize(trust.runtimeSize))errs.push(problem2("trust.runtimeSize","required for gzip runtime"));if(!goodSize(trust.runtimeDecodedSize))errs.push(problem2("trust.runtimeDecodedSize","required for gzip runtime"));if(!trust.runtimeDecodedDigest)errs.push(problem2("trust.runtimeDecodedDigest","required for gzip runtime"))}for(let key2 of["poster","detailUrl"]){let value=entry[key2];if(value&&/^file:|^javascript:|^data:/i.test(value))errs.push(problem2(key2,"unsafe URL"))}if(!entry.compatibility?.eikon)errs.push(problem2("compatibility.eikon","required"));if(entry.compatibility?.eikon&&!/>=?\s*1/.test(entry.compatibility.eikon))errs.push(problem2("compatibility.eikon","must support launch major version 1"));if(errs.length)throw new EikonValidationError(errs);return entry}function normalizeCatalogEntry(input,base,opts={}){if(isObj3(input)&&"kind"in input&&input.kind===CATALOG_KIND)return validateCatalogEntry(input,opts);if(isObj3(input)&&"manifest"in input)return fromPackage(input,base,opts);return fromLegacy(input,base,opts)}function searchCatalogEntries(entries,query){let q2=query.trim().toLowerCase();if(!q2)return[...entries];return entries.filter((entry)=>[entry.name,entry.title,entry.author,entry.description,...entry.tags??[]].some((value)=>value?.toLowerCase().includes(q2)))}async function loadCatalogEntries(base,fetcher=fetch,opts={}){let root=trimSlash(publicCatalogUrl(base,void 0,opts)),res=await fetcher(`${root}/index.json`);if(res.url)publicCatalogUrl(res.url,void 0,opts);if(!res.ok)throw Error(`catalog: ${res.status} loading ${root}/index.json`);let items=await res.json();if(!Array.isArray(items))throw new EikonValidationError([problem2("catalog","index array required")]);return items.map((item)=>normalizeCatalogEntry(item,`${root}/`,opts))}function searchCatalog(entries,query){return searchCatalogEntries(entries,query)}async function loadCatalog(base=DEFAULT_PUBLIC_CATALOG,fetcher=fetch,opts={}){let root=trimSlash(publicCatalogUrl(base,void 0,opts)),res=await fetcher(`${root}/index.json`);if(res.url)publicCatalogUrl(res.url,void 0,opts);if(!res.ok)throw Error(`catalog: HTTP ${res.status}`);let items=await res.json();if(!Array.isArray(items))throw new EikonValidationError([problem2("catalog","index array required")]);let entries=items.map((item)=>{if(isObj3(item)&&"kind"in item&&item.kind===CATALOG_KIND)return publicFromEntry(normalizeCatalogEntry(item,void 0,opts),item);if(isObj3(item)&&"manifest"in item)return publicFromEntry(normalizeCatalogEntry(item,`${root}/`,opts),item);return catalogEntry(item,root,opts)});return{base:root,entries,async load(entry){let item=typeof entry==="string"?entries.find((e)=>e.identityKey===entry||e.sourceKey===entry||e.id===entry||e.name===entry):entry;if(!item)throw Error(`catalog: unknown eikon "${entry}"`);return(await loadRuntimeArtifact(item,fetcher,{allowPrivate:opts.allowPrivate})).text}}}var clean2=(value)=>value.trim(),safe=(value)=>/^[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]+$/.test(value)&&!/[\u0000-\u001f\u007f\\]/.test(value),esc=(value)=>value.replace(/[#?].*$/,"").split("/").some((part)=>part===".."),key2=(kind,value)=>`${kind}:${value}`;function cleanUrl(raw){try{let url2=new URL(raw);for(let key3 of[...url2.searchParams.keys()])if(/token|secret|key|credential|password/i.test(key3))url2.searchParams.set(key3,"[redacted]");return`${url2.origin}${url2.pathname}${url2.search}`}catch{return raw.replace(/([?&][^=]*(?:token|secret|key|credential|password)[^=]*=)[^&\s]+/ig,"$1[redacted]")}}function http(raw){try{let rawPath=raw.split(/[?#]/,1)[0]??raw,decoded=(()=>{try{return decodeURIComponent(rawPath)}catch{return rawPath}})(),url2=new URL(raw);if(url2.protocol!=="http:"&&url2.protocol!=="https:")return;if(!safe(raw)||esc(rawPath)||esc(decoded)||esc(url2.pathname)||/%5c/i.test(raw))throw Error(`unsafe source URL: ${cleanUrl(raw)}`);return url2.href}catch(err){if(err instanceof Error&&err.message.startsWith("unsafe"))throw err;return}}function github(raw){let spec2=raw.replace(/^github:/,""),input=spec2.replace(/^https:\/\/github\.com\//,"").replace(/^git@github\.com:/,"").replace(/^github\.com\//,"");if(input===spec2&&!raw.startsWith("github:"))return;let[path6,query=""]=input.split("?"),[head,hash]=path6.split("#"),parts2=head.replace(/\.git$/,"").split("/").filter(Boolean);if(parts2.length<2)return;let owner=parts2[0],repo=parts2[1].replace(/\.git$/,""),pathSelector=parts2.slice(2).join("/")||void 0,params=new URLSearchParams(query),ref=hash?decodeURIComponent(hash):void 0,selector=params.get("selector")?decodeURIComponent(params.get("selector")):pathSelector;for(let part of[owner,repo,ref,selector].filter(Boolean))if(!/^[A-Za-z0-9._/-]+$/.test(part)||part.split("/").some((x2)=>!x2||x2==="."||x2===".."||x2.startsWith("-")))throw Error(`unsafe GitHub source: ${raw}`);let suffix2=`${owner}/${repo}${ref?`#${ref}`:""}${selector?`?selector=${selector}`:""}`;return{kind:"github",spec:raw,sourceKey:key2("github",suffix2),owner,repo,...ref?{ref}:{},...selector?{selector}:{}}}function parseSourceSpec(raw){let spec2=clean2(raw);if(!spec2)throw Error("source spec required");if(!safe(spec2))throw Error(`unsafe source spec: ${spec2}`);if(/^(npm|registry):/.test(spec2)){let body=spec2.replace(/^(npm|registry):/,""),at=body.startsWith("@")?body.indexOf("@",1):body.lastIndexOf("@"),name=at>0?body.slice(0,at):body,range=at>0?body.slice(at+1):void 0;if(!name)throw Error(`registry source name required: ${spec2}`);return{kind:"registry",spec:spec2,sourceKey:key2("registry",body),name,...range?{range}:{},supported:!1}}if(spec2.startsWith("catalog+")){let[url3,name]=spec2.slice(8).split("#"),catalogUrl=http(url3)??(()=>{throw Error(`catalog URL must be http(s): ${spec2}`)})();return{kind:"catalog",spec:spec2,sourceKey:key2("catalog",`${catalogUrl}#${name??""}`),catalogUrl,...name?{name}:{}}}if(spec2.startsWith("catalog:")){let name=spec2.slice(8);if(!name)throw Error("catalog source name required");return{kind:"catalog",spec:spec2,sourceKey:key2("catalog",name),name}}if(spec2.startsWith("pkg:")){let url3=http(spec2.slice(4))??(()=>{throw Error(`package URL must be http(s): ${spec2}`)})();return{kind:"package-url",spec:spec2,sourceKey:key2("package",url3),url:url3}}let gh=github(spec2);if(gh)return gh;let url2=http(spec2);if(url2)return{kind:"package-url",spec:spec2,sourceKey:key2("package",url2),url:url2};if(spec2.startsWith("file://")||spec2.startsWith("/")||spec2.startsWith("./")||spec2.startsWith("../"))return{kind:"local",spec:spec2,sourceKey:key2("local",spec2),path:spec2.replace(/^file:\/\//,"")};if(!/[/:]/.test(spec2))return{kind:"catalog",spec:spec2,sourceKey:key2("catalog",spec2),name:spec2};throw Error(`unsupported source spec: ${spec2}`)}function assertWritableScope(scope="profile"){if(scope==="project-reserved")throw Error("project-reserved Eikon scope is deferred until project trust policy exists");return scope}var sha2562=(data2)=>`sha256:${createHash2("sha256").update(data2).digest("hex")}`,NAME_RE4=/^[a-z0-9][a-z0-9-]{0,63}$/,cleanUrl2=(raw)=>{try{let u3=new URL(raw);for(let key3 of[...u3.searchParams.keys()])if(/token|secret|key|credential|password/i.test(key3))u3.searchParams.set(key3,"[redacted]");if(u3.username||u3.password)return`${u3.protocol}//[redacted]@${u3.host}${u3.pathname}${u3.search}${u3.hash}`;return u3.href}catch{return raw.replace(/\/\/[^/@\s]+@/,"//[redacted]@").replace(/([?&][^=]*(?:token|secret|key|credential|password)[^=]*=)[^&\s]+/ig,"$1[redacted]")}};function assertDownloadUrl(raw,opts){if(/[\u0000-\u001f\u007f]/.test(raw)||raw.includes("\\")||/%5c/i.test(raw))throw Error(`download URL contains unsafe characters: ${cleanUrl2(raw)}`);if(pathParts(raw).some((path6)=>path6.split(/[\\/]/).some((part)=>part==="..")))throw Error(`download URL path escape: ${cleanUrl2(raw)}`);let url2=new URL(raw);if(pathParts(url2.pathname).some((path6)=>path6.split(/[\\/]/).some((part)=>part==="..")))throw Error(`download URL path escape: ${cleanUrl2(raw)}`);if(url2.protocol!=="https:"&&url2.protocol!=="http:")throw Error(`download URL must use https: ${cleanUrl2(raw)}`);if(url2.username||url2.password)throw Error(`download URL cannot include credentials: ${cleanUrl2(raw)}`);if(!opts.allowPrivate&&privateHost(url2.hostname))throw Error(`download URL cannot use private host: ${url2.hostname}`);if(url2.protocol==="http:"&&!privateHost(url2.hostname))throw Error(`download URL must use https: ${cleanUrl2(raw)}`);return url2}async function downloadBytes(raw,opts={}){let fetcher=opts.fetcher??fetch,maxBytes=opts.maxBytes??104857600,maxRedirects=opts.maxRedirects??5,url2=assertDownloadUrl(raw,opts);for(let i=0;i<=maxRedirects;i++){let res=await fetcher(url2.href,{redirect:"manual"});if(res.status>=300&&res.status<400&&res.headers.get("location")){url2=assertDownloadUrl(new URL(res.headers.get("location"),url2).href,opts);continue}if(!res.ok)throw Error(`download failed ${res.status}: ${cleanUrl2(url2.href)}`);let enc=res.headers.get("content-encoding");if(opts.rejectContentEncoding&&enc&&enc.toLowerCase()!=="identity")throw Error(`download content-encoding not allowed for artifact bytes: ${enc}`);if(Number(res.headers.get("content-length")??0)>maxBytes)throw Error(`download byte limit exceeded: ${cleanUrl2(url2.href)}`);let buf=new Uint8Array(await res.arrayBuffer());if(buf.length>maxBytes)throw Error(`download byte limit exceeded: ${cleanUrl2(url2.href)}`);return buf}throw Error(`download redirect limit exceeded: ${cleanUrl2(raw)}`)}function safeSelector(selector){if(!selector)return;if(/[\u0000-\u001f\u007f]|%|\\/.test(selector))throw Error("unsafe selector");if(selector.split("/").some((p)=>!p||p==="."||p===".."||p.startsWith("-")))throw Error("unsafe selector");let parts2=selector.split("/");if(parts2.length>2||parts2.some((p)=>!/^[A-Za-z0-9._-]+$/.test(p)))throw Error("unsafe selector");return selector}function resolveGithubSource(raw){if(/[\u0000\r\n]/.test(raw))throw Error("unsafe GitHub source");let owner,repo,rest="",m2=raw.match(/^github\.com\/([^/]+)\/([^/]+)(?:\/(.+))?$/);if(m2)owner=m2[1],repo=m2[2],rest=m2[3]??"";if(m2=raw.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/(.+))?$/),!owner&&m2)owner=m2[1],repo=m2[2],rest=m2[3]??"";if(m2=raw.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?(?:\/(.+))?$/),!owner&&m2)owner=m2[1],repo=m2[2],rest=m2[3]??"";if(!owner||!repo)throw Error("only github.com repository sources are supported");if(repo=repo.replace(/\.git$/,""),![owner,repo].every((p)=>/^[A-Za-z0-9._-]+$/.test(p))||owner.startsWith("-")||repo.startsWith("-"))throw Error("unsafe GitHub repository");let selector=safeSelector(rest.replace(/^\/+/,"")||void 0);return{owner,repo,selector,cloneUrl:`https://github.com/${owner}/${repo}.git`,display:`github.com/${owner}/${repo}${selector?`/${selector}`:""}`}}function entries(man){let pkg=validatePackageManifest(man),xs=[];if(pkg.source?.base)xs.push(["base",pkg.source.base]);for(let k2 of STATES){let f=pkg.source?.states?.[k2]?.file;if(f)xs.push([k2,f])}return xs}function manifest(value){return validatePackageManifest(value)}function installManifest(man,origin){let{license:_license,provenance:_provenance,...clean3}=man;return{...clean3,origin}}var gitish=(s)=>{if(/^(?:github\.com|https:\/\/github\.com|git@github\.com:)/.test(s))return!0;return/^git@|^ssh:\/\/|^git:\/\/|\.git$/.test(s)||/^(https?:\/\/)?(gitlab|bitbucket)\.com\/[\w.-]+\/[\w.-]+\/?$/.test(s)};async function defaultClone(url2,dst){let[raw,ref]=url2.split("#",2),source=resolveGithubSource(raw),args=["git","clone","--depth","1",...ref?["--branch",ref]:[],"--",source.cloneUrl,dst],p=Bun.spawn(args,{stdout:"pipe",stderr:"pipe"}),[code,err]=await Promise.all([p.exited,new Response(p.stderr).text()]);if(code!==0)throw Error(`git clone failed: ${err.trim()}`);let sha=await new Response(Bun.spawn(["git","-C",dst,"rev-parse","HEAD"],{stdout:"pipe"}).stdout).text();return rmSync(join7(dst,".git"),{recursive:!0,force:!0}),{dir:dst,sha:sha.trim()||void 0,cleanup:!0}}function readJson(path6){return JSON.parse(readFileSync3(path6,"utf8"))}function asPackageIndex(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(!Array.isArray(raw.versions))return;return raw}function latestPackageFromIndex(path6){let rel=asPackageIndex(readJson(path6))?.versions?.at(-1)?.manifest;if(!rel||!isSafeRelativePath(rel))throw Error(`${path6}: package index has no safe manifest path`);return join7(dirname5(path6),rel)}function catalogMatches(entry,selector){let slug=selector.split("/").at(-1);return[entry.id,entry.name,entry.sourceKey,entry.packageUrl.split("/packages/").at(-1)?.replace(/\/[^/]+\.json$/,"")].some((key3)=>key3===selector||key3===slug||key3?.endsWith(`/${selector}`)||key3?.endsWith(`/${slug}`))}function packageResolution(repo,selector){let parts2=selector.split("/");if(parts2.length===2){let idx=join7(repo,"packages",parts2[0],parts2[1],"index.json");if(!existsSync8(idx))return;let path7=latestPackageFromIndex(idx);return{manifest:manifest(readJson(path7)),staged:dirname5(path7),root:`packages/${parts2[0]}/${parts2[1]}/index.json`}}let matches=[],packages=join7(repo,"packages");if(existsSync8(packages))for(let ns2 of readdirSync2(packages,{withFileTypes:!0})){if(!ns2.isDirectory())continue;let idx=join7(packages,ns2.name,selector,"index.json");if(existsSync8(idx))matches.push(idx)}if(matches.length>1)throw Error(`ambiguous package selector "${selector}"; use namespace/name`);if(!matches.length)return;let path6=latestPackageFromIndex(matches[0]),ns=basename5(dirname5(dirname5(path6)));return{manifest:manifest(readJson(path6)),staged:dirname5(path6),root:`packages/${ns}/${selector}/index.json`}}function catalogResolution(repo,selector){for(let root of["eikons/index.json","registry.json","index.json"]){let path6=join7(repo,root);if(!existsSync8(path6))continue;let raw=readJson(path6);if(!Array.isArray(raw))continue;let matches=raw.map((item)=>{let any=item;if(any.packageUrl?.startsWith("../")||any.package_url?.startsWith("../")){let rel=any.packageUrl??any.package_url;return normalizeCatalogEntry({...item,packageUrl:`https://github.local/${rel.replace(/^\.\.\//,"")}`},"https://github.local/")}return normalizeCatalogEntry(item,"https://github.local/")}).filter((entry2)=>catalogMatches(entry2,selector));if(matches.length>1)throw Error(`ambiguous catalog selector "${selector}"`);if(!matches.length)continue;let entry=matches[0],pkgPath,url2=new URL(entry.packageUrl);if(pkgPath=join7(repo,url2.pathname.replace(/^\//,"")),!existsSync8(pkgPath))pkgPath=join7(dirname5(path6),entry.packageUrl);return{entry,manifest:manifest(readJson(pkgPath)),staged:dirname5(pkgPath),root}}return}function trustFor(man,staged,base){let pkg=validatePackageManifest(man),files=pkg.files??[];if(!files.length)return{state:"unverified",reason:"package descriptors missing"};if(files.filter((file)=>!file.digest||typeof file.size!=="number").length)return{state:"unverified",reason:"package descriptor digest or size missing"};if(base)return{state:"unverified",reason:"remote package files not downloaded yet"};return verifyPackageFiles(pkg,staged)}async function verifyRemotePackageFiles(pkg,base,opts){let files=pkg.files??[];if(!files.length)return{trust:{state:"unverified",reason:"package descriptors missing"}};if(files.filter((file)=>!file.digest||typeof file.size!=="number").length)return{trust:{state:"unverified",reason:"package descriptor digest or size missing"}};let verified=[],data2=new Map;for(let file of files){if(!isSafeRelativePath(file.path))throw Error(`mismatch: unsafe descriptor path ${file.path}`);let buf=await downloadBytes(new URL(file.path,base).href,{...opts,rejectContentEncoding:file.role==="runtime"&&!!file.digest});if(typeof file.size==="number"&&buf.length!==file.size)throw Error(`mismatch: size ${file.path}`);if(file.digest&&sha2562(buf)!==file.digest)throw Error(`mismatch: digest ${file.path}`);data2.set(file.path,buf),verified.push(file.path)}return{trust:{state:"verified",verified},files:data2}}function assertRemotePackageWriteCoverage(pkg,files){for(let rel of new Set([pkg.entrypoints.default,...entries(pkg).map(([,rel2])=>rel2)]))if(!files?.has(rel))throw Error(`missing verified descriptor for remote package write: ${rel}`)}function assertVerifiedPackageWriteCoverage(pkg,trust){if(trust.state!=="verified")return;let verified=new Set(trust.verified??[]);for(let rel of new Set([pkg.entrypoints.default,...entries(pkg).map(([,rel2])=>rel2)]))if(!verified.has(rel))throw Error(`missing verified descriptor for package write: ${rel}`)}function installName(name){if(!NAME_RE4.test(name))throw Error(`${name||"<empty>"}: invalid eikon name`);return name}function cleanupResolved(r){if(r.tmp)rmSync(r.cleanup??r.staged,{recursive:!0,force:!0})}function assertSafePackageFile(staged,rel){let parts2=rel.split("/"),current=staged;for(let part of parts2){current=join7(current,part);let stat=lstatSync(current);if(stat.isSymbolicLink())throw Error(`mismatch: symlink or special file ${rel}`);if(part!==parts2.at(-1)&&!stat.isDirectory())throw Error(`mismatch: symlink or special file ${rel}`);if(part===parts2.at(-1)&&!stat.isFile())throw Error(`mismatch: symlink or special file ${rel}`)}return current}function verifyPackageFiles(pkg,staged){let verified=[];for(let file of pkg.files??[]){if(!isSafeRelativePath(file.path))throw Error(`mismatch: unsafe descriptor path ${file.path}`);let path6=assertSafePackageFile(staged,file.path),data2=readFileSync3(path6);if(typeof file.size==="number"&&data2.length!==file.size)throw Error(`mismatch: size ${file.path}`);if(file.digest&&sha2562(data2)!==file.digest)throw Error(`mismatch: digest ${file.path}`);if(file.digest&&typeof file.size==="number")verified.push(file.path)}return verified.length?{state:"verified",verified}:{state:"unverified",reason:"package descriptor digest or size missing"}}function locate(dir){if(existsSync8(join7(dir,"manifest.json")))return dir;for(let e of readdirSync2(dir,{withFileTypes:!0}))if(e.isDirectory()&&existsSync8(join7(dir,e.name,"manifest.json")))return join7(dir,e.name);throw Error(`no manifest.json in ${dir} (or one level deep)`)}async function catalog(name,url2,opts={}){let base=url2.replace(/\/?$/,"/"),allow=opts.downloader?.allowPrivate||/^http:\/\/localhost[:/]/.test(base),dl=opts.downloader??(allow?{allowPrivate:!0}:{}),entry=(await loadCatalogEntries(base,async(input)=>{let raw=typeof input==="string"?input:input instanceof URL?input.href:input.url;return new Response(new TextDecoder().decode(await downloadBytes(raw,dl)))},{allowPrivate:allow})).find((e)=>e.name===name||e.id===name||e.sourceKey===name);if(!entry)throw Error(`catalog: no eikon named "${name}"`);return entry}async function resolvePackageUrl(entry,opts={},source){let at=new Date().toISOString(),bytes=await downloadBytes(entry.packageUrl,opts.downloader??(/^http:\/\/localhost[:/]/.test(entry.packageUrl)?{allowPrivate:!0}:void 0));if(entry.trust?.manifestDigest&&sha2562(bytes)!==entry.trust.manifestDigest)throw Error("mismatch: package manifest digest");let man=manifest(JSON.parse(new TextDecoder().decode(bytes))),base=new URL(".",entry.packageUrl).href,pkg=man,desc=pkg.files?.find((file)=>file.role==="runtime"&&file.path===pkg.entrypoints?.default),version=typeof man.version==="string"?man.version:man.version!=null?String(man.version):void 0;return{name:man.name,manifest:man,staged:"",base,origin:{source:source?.source??entry.packageUrl,sourceSpec:source?.spec??entry.packageUrl,at,kind:source?.kind??"default-catalog",sourceKey:entry.sourceKey,identityKey:entry.sourceKey||entry.id,packageUrl:entry.packageUrl,runtimeUrl:entry.runtimeUrl,contentDigest:desc?.digest,resolvedVersion:version},trust:trustFor(man,"",base)}}async function resolve6(src,opts={}){let at=new Date().toISOString(),local=src.replace(/^file:\/\//,"");if(!gitish(src)&&existsSync8(local)&&statSync(local).isDirectory()){let staged=locate(local),man=manifest(JSON.parse(readFileSync3(join7(staged,"manifest.json"),"utf8")));return{name:man.name,manifest:man,staged,origin:{source:src,sourceSpec:src,at,kind:"local",sourceKey:`local:${src}`},trust:trustFor(man,staged)}}let parsed=parseSourceSpec(src);if(parsed.kind==="registry")throw Error("registry Eikon sources are reserved for a future package backend");let sourceSpec=parsed.spec;if(parsed.kind==="catalog"){let base=opts.catalog??parsed.catalogUrl??DEFAULT_CATALOG;return resolvePackageUrl(await catalog(parsed.name??src,base,opts),opts,{spec:sourceSpec,source:parsed.name??src,kind:"default-catalog"})}if(parsed.kind==="package-url"){let raw=new URL(parsed.url),href=raw.pathname.endsWith(".json")?raw.href:new URL("manifest.json",parsed.url.replace(/\/?$/,"/")).href,base=new URL(".",href).href,bytes=await downloadBytes(href,opts.downloader??(/^http:\/\/localhost[:/]/.test(href)?{allowPrivate:!0}:void 0)),man=manifest(JSON.parse(new TextDecoder().decode(bytes))),version=typeof man.version==="string"?man.version:man.version!=null?String(man.version):void 0;return{name:man.name,manifest:man,staged:"",base,origin:{source:src,sourceSpec,at,kind:"catalog-package",sourceKey:parsed.sourceKey,packageUrl:href,resolvedVersion:version},trust:trustFor(man,"",base)}}if(parsed.kind==="github"||gitish(src)){let gh;if(parsed.kind==="github")gh={owner:parsed.owner,repo:parsed.repo,selector:parsed.selector,cloneUrl:`https://github.com/${parsed.owner}/${parsed.repo}.git`,display:`github.com/${parsed.owner}/${parsed.repo}${parsed.selector?`/${parsed.selector}`:""}`};else try{gh=resolveGithubSource(src)}catch{}let tmp=mkdtempSync(join7(tmpdir(),"eikon-"));if(!gh){let p=Bun.spawn(["git","clone","--depth","1","--",src,tmp],{stdout:"pipe",stderr:"pipe"}),[code,err]=await Promise.all([p.exited,new Response(p.stderr).text()]);if(code!==0)throw Error(`git clone failed: ${err.trim()}`);let sha=await new Response(Bun.spawn(["git","-C",tmp,"rev-parse","HEAD"],{stdout:"pipe"}).stdout).text();rmSync(join7(tmp,".git"),{recursive:!0,force:!0});let staged2=locate(tmp),man2=manifest(JSON.parse(readFileSync3(join7(staged2,"manifest.json"),"utf8")));return{name:man2.name,manifest:man2,staged:staged2,tmp:!0,cleanup:tmp,origin:{source:src,sourceSpec,at,kind:"github-package",sourceKey:parsed.sourceKey,sha:sha.trim()||void 0,resolvedRef:sha.trim()||void 0},trust:trustFor(man2,staged2)}}let cloneUrl=parsed.kind==="github"&&parsed.ref?`${gh.cloneUrl}#${parsed.ref}`:gh.cloneUrl,cloned=await(opts.clone??defaultClone)(cloneUrl,tmp),repo=cloned.dir;if(gh.selector){let selected=catalogResolution(repo,gh.selector);if(selected)return{name:selected.manifest.name,manifest:selected.manifest,staged:selected.staged,tmp:cloned.cleanup!==!1,cleanup:cloned.cleanup!==!1?repo:void 0,origin:{source:src,sourceSpec,at,kind:"github-catalog",sha:cloned.sha,resolvedRef:cloned.sha??(parsed.kind==="github"?parsed.ref:void 0),repo:gh.display,selector:gh.selector,catalogRoot:selected.root,sourceKey:selected.entry.sourceKey,identityKey:selected.entry.sourceKey||selected.entry.id,packageUrl:selected.entry.packageUrl,runtimeUrl:selected.entry.runtimeUrl},trust:trustFor(selected.manifest,selected.staged)};let indexed=packageResolution(repo,gh.selector);if(indexed)return{name:indexed.manifest.name,manifest:indexed.manifest,staged:indexed.staged,tmp:cloned.cleanup!==!1,cleanup:cloned.cleanup!==!1?repo:void 0,origin:{source:src,sourceSpec,at,kind:"github-catalog",sha:cloned.sha,resolvedRef:cloned.sha??(parsed.kind==="github"?parsed.ref:void 0),repo:gh.display,selector:gh.selector,catalogRoot:indexed.root,sourceKey:parsed.sourceKey},trust:trustFor(indexed.manifest,indexed.staged)};if(cloned.cleanup!==!1)rmSync(repo,{recursive:!0,force:!0});throw Error(`no eikon named "${gh.selector}" in GitHub catalog`)}let staged=locate(repo),man=manifest(JSON.parse(readFileSync3(join7(staged,"manifest.json"),"utf8")));return{name:man.name,manifest:man,staged,tmp:cloned.cleanup!==!1,cleanup:cloned.cleanup!==!1?repo:void 0,origin:{source:src,sourceSpec,at,kind:"github-package",sourceKey:parsed.sourceKey,sha:cloned.sha,resolvedRef:cloned.sha??(parsed.kind==="github"?parsed.ref:void 0),repo:gh.display},trust:trustFor(man,staged)}}throw Error(`cannot resolve "${src}": expected catalog name, git URL, local dir, or http(s) base`)}var peeked=new Map;function peek3(src,opts){let hit=peeked.get(src);if(hit)return hit;let p=resolve6(src,opts).then(async(r)=>{let xs=entries(r.manifest);if(r.base){let sizes=await Promise.all(xs.map(([,rel])=>fetch(new URL(rel,r.base).href,{method:"HEAD"}).then((h2)=>Number(h2.headers.get("content-length")??0)).catch(()=>0)));return{n:xs.length,bytes:sizes.reduce((a,b2)=>a+b2,0)}}let bytes=xs.reduce((a,[,rel])=>{let p2=join7(r.staged,rel);return a+(existsSync8(p2)?statSync(p2).size:0)},0);return{n:xs.length,bytes}}).catch(()=>{return});return peeked.set(src,p),p}async function install(src,root,opts={}){let scope=assertWritableScope(opts.scope??"profile"),r=await resolve6(src,opts);r.origin.scope=scope;let name=installName(opts.name??r.name);mkdirSync3(root,{recursive:!0});let dst=join7(root,name),tmp=mkdtempSync(join7(root,`.${name}-`)),srcd=join7(tmp,"source"),old=join7(root,`.${name}.old-${process.pid}-${Date.now()}`);try{let remote,launchBytes,man=validatePackageManifest(r.manifest),dl=opts.downloader??(/^http:\/\/localhost[:/]/.test(r.base??"")?{allowPrivate:!0}:{});if(r.base)remote=await verifyRemotePackageFiles(man,r.base,dl),assertRemotePackageWriteCoverage(man,remote.files),validatePackageManifest(man,{registry:!0}),r.trust=remote.trust;if(!r.base&&r.staged)r.trust=verifyPackageFiles(man,r.staged),assertVerifiedPackageWriteCoverage(man,r.trust);let rel=man.entrypoints.default,desc=man.files?.find((file)=>file.role==="runtime"&&file.path===rel);if(r.base)launchBytes=remote.files.get(rel);else launchBytes=readFileSync3(assertSafePackageFile(r.staged,rel));parseRuntimeBytes(launchBytes,{descriptor:desc}),mkdirSync3(srcd,{recursive:!0}),writeFileSync4(join7(tmp,`${name}.eikon`),launchBytes);let xs=entries(r.manifest),sources={},done=0,bytes=0,tick2=()=>opts.progress?.(++done,xs.length);if(opts.media!==!1)await Promise.all(xs.map(async([role,rel2])=>{let fname=`${role}${extname2(rel2).toLowerCase()}`,to=join7(srcd,fname);if(r.base){let dl2=opts.downloader??(/^http:\/\/localhost[:/]/.test(r.base)?{allowPrivate:!0}:{}),buf=remote?remote.files.get(rel2):await downloadBytes(new URL(rel2,r.base).href,dl2);await Bun.write(to,buf),bytes+=buf.length}else{let from2=assertSafePackageFile(r.staged,rel2);if(!existsSync8(from2))throw Error(`${rel2}: missing in ${r.staged}`);copyFileSync(from2,to),bytes+=statSync(to).size}sources[role]=fname,tick2()}));let out=installManifest(r.manifest,{...r.origin,trust:r.trust.state});if(writeFileSync4(join7(tmp,"manifest.json"),JSON.stringify(out,null,2)+`
|
|
4088
|
-
`),existsSync8(dst))renameSync2(dst,old);try{renameSync2(tmp,dst)}catch(err){if(existsSync8(old))renameSync2(old,dst);throw err}if(existsSync8(old))rmSync(old,{recursive:!0,force:!0});return cleanupResolved(r),{...r,name,dir:dst,sources,n:xs.length,bytes}}catch(err){throw rmSync(tmp,{recursive:!0,force:!0}),cleanupResolved(r),err}}function dirty(dir){let mf=join7(dir,"manifest.json");if(!existsSync8(mf))return!1;let man=JSON.parse(readFileSync3(mf,"utf8"));if(!man.origin?.at)return!1;let since=Date.parse(man.origin.at);for(let e of readdirSync2(dir,{withFileTypes:!0,recursive:!0}))if(statSync(join7(e.parentPath??dir,e.name)).mtimeMs>since+2000)return!0;return!1}import{existsSync as existsSync9,lstatSync as lstatSync2,readFileSync as readFileSync4}from"fs";import{basename as basename6,dirname as dirname6,join as join8,relative as relative2,resolve as resolve7,sep}from"path";var DEFAULT_SUBMIT_REPO=process.env.EIKON_REPO??"liftaris/eikon",DEFAULT_MAX_BUNDLE_BYTES=33554432,SECRET=/(\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|id_rsa$|id_ed25519$|token|secret|credential|password)/i
|
|
4089
|
-
`);return{bundle,title,body}}async function gh(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?new TextEncoder().encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code!==0)throw Error(`gh ${args[0]} failed: ${err.trim()||out.trim()}`);return out.trim()}async function existingSha(run,fork,branch,path6){try{let out=await run(["api","-X","GET",`repos/${fork}/contents/${path6}`,"-f",`ref=${branch}`]),json=JSON.parse(out);return typeof json.sha==="string"?json.sha:void 0}catch{return}}function githubSubmitBackend(repo=DEFAULT_SUBMIT_REPO,run=gh){return{async check(){try{return await run(["auth","status"]),{ok:!0}}catch(err){return{ok:!1,reason:err instanceof Error?err.message:String(err)}}},async create(req){let name=req.bundle.meta.name,branch=`submit/${name}`;await run(["repo","fork",repo,"--clone=false"]).catch(()=>"");let user=await run(["api","user","-q",".login"]),fork=`${user}/${repo.split("/")[1]}`,main2=await run(["api",`repos/${repo}/git/ref/heads/main`,"-q",".object.sha"]);await run(["api","-X","POST",`repos/${fork}/git/refs`,"-f",`ref=refs/heads/${branch}`,"-f",`sha=${main2}`]).catch(()=>"");for(let file of req.bundle.files){let dest=`eikons/${name}/${file.path}`,content=Buffer.from(await Bun.file(file.abs).arrayBuffer()).toString("base64"),sha=await existingSha(run,fork,branch,dest),args=["api","-X","PUT",`repos/${fork}/contents/${dest}`,"-f",`message=eikons: submit ${name}`,"-f",`branch=${branch}`,"-f",`content=${content}`];if(sha)args.push("-f",`sha=${sha}`);await run(args)}return{kind:"submitted",url:await run(["pr","create","-R",repo,"-H",`${user}:${branch}`,"-B","main","-t",req.title,"-b",req.body]),request:req}}}}var STREAM_EXT=/\.eikon$/;function readManifestEntrypoint(path6){try{let entrypoints=JSON.parse(readFileSync5(path6,"utf8")).entrypoints;if(!entrypoints||typeof entrypoints!=="object"||Array.isArray(entrypoints))return;let value=entrypoints.default;return typeof value==="string"&&STREAM_EXT.test(value)?value:void 0}catch{return}}function parseEikon(text3){let first=text3.split(`
|
|
4090
|
-
`,1)[0];if((first?JSON.parse(first):{}).type==="header"){let e2=parseLaunchStream(text3);return{meta:e2.meta,states:e2.clips,resolve:(signal)=>{try{return e2.clips.get(resolveSignal(e2,signal).clip)}catch{return}}}}let e=parse3(text3);return{meta:e.meta,states:e.clips,resolve:(signal)=>e.clips.get(signal.replace(/^state\./,""))}}function parseEikonFile(path6){return parseEikon(decodeRuntimeFile(path6))}function listEikons(dirs){return dirs.flatMap((dir)=>{let ents;try{ents=readdirSync3(dir,{recursive:!0})}catch{return[]}let paths=ents.map((e)=>join9(dir,e)),streamFiles=paths.filter((path6)=>STREAM_EXT.test(path6)),packageEntrypoints=new Map;for(let manifest2 of paths.filter((path6)=>path6.endsWith("manifest.json"))){let entrypoint=readManifestEntrypoint(manifest2);if(entrypoint){let root=dirname7(manifest2);packageEntrypoints.set(root,join9(root,entrypoint))}}let packageRootFor=(path6)=>{for(let root of packageEntrypoints.keys()){let rel=relative3(root,path6);if(rel&&!rel.startsWith("..")&&!isAbsolute2(rel))return root}return};return streamFiles.sort((a,b2)=>a.localeCompare(b2)).filter((path6)=>{let packageRoot=packageRootFor(path6);return packageRoot?path6===packageEntrypoints.get(packageRoot):!0}).map((path6)=>({path:path6,meta:peek2(resolve8(path6))})).filter((x2)=>x2.meta!==null)})}var BLANK2={fps:1,loopFrom:1,frames:[[""]]},DEFAULT_EIKON=(()=>{try{return parseEikon(default_default)}catch{return}})(),STATE_FRAMES={idle:DEFAULT_EIKON?.states.get("idle")??BLANK2,listening:DEFAULT_EIKON?.states.get("listening")??BLANK2,thinking:DEFAULT_EIKON?.states.get("thinking")??BLANK2,speaking:DEFAULT_EIKON?.states.get("speaking")??BLANK2,working:DEFAULT_EIKON?.states.get("working")??BLANK2,error:DEFAULT_EIKON?.states.get("error")??BLANK2};init_perf();var AnimatedAvatar=import_react29.memo(({state="idle",eikon,onHold})=>{let theme=useTheme().theme,[frame,setFrame]=import_react29.useState(0),timer2=import_react29.useRef(null),holdRef=import_react29.useRef(onHold);holdRef.current=onHold;let signal=`state.${state}`,clip=eikon?.resolve(signal)??eikon?.states.get(state)??STATE_FRAMES[state],{frames,fps,loopFrom}=clip,count2=frames.length,animate=usePref("animations")!==!1,targetFps=usePref("targetFps")??30,dt=1000/Math.max(1,Math.min(fps,targetFps));import_react29.useEffect(()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null;if(setFrame(0),!animate||count2<2)return;if(count("avatar:timer:start"),process.env.HERM_TEST_PERF==="1")globalThis.__hermAvatarTimerStarts=(globalThis.__hermAvatarTimerStarts??0)+1;let idx=0,tick2=()=>{if(count("avatar:tick"),idx++,idx>=count2){if(loopFrom>=count2){setFrame(count2-1),holdRef.current?.(state);return}idx=loopFrom}setFrame(idx),timer2.current=setTimeout(tick2,dt)};return timer2.current=setTimeout(tick2,dt),()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null,count("avatar:timer:stop")}},[state,count2,loopFrom,animate,dt]);let end=mark("avatar:render"),lines3=frames[Math.min(frame,count2-1)]??[],result=$jsx("box",{flexDirection:"column",children:lines3.map((line,i)=>$jsx("text",{children:$jsx("span",{fg:theme.hermAvatar,children:line})},i))});return end(),result});var import_react30=__toESM(require_react_production(),1);import{watch}from"fs";var TIMEOUT=500;async function git(cwd,...args){let p=Bun.spawn(["git","-C",cwd,...args],{stdout:"pipe",stderr:"ignore"}),t2=setTimeout(()=>p.kill(),TIMEOUT),out=await new Response(p.stdout).text();return clearTimeout(t2),await p.exited===0?out.trim():null}async function branch(cwd){let b2=await git(cwd,"rev-parse","--abbrev-ref","HEAD");return!b2||b2==="HEAD"?null:b2}async function gitdir(cwd){return git(cwd,"rev-parse","--absolute-git-dir")}function useGitBranch(cwd){let[val,set2]=import_react30.useState(null);return import_react30.useEffect(()=>{if(!cwd){set2(null);return}let dead=!1,w2,read=()=>branch(cwd).then((b2)=>{if(!dead)set2(b2)});return read(),gitdir(cwd).then((dir)=>{if(dead||!dir)return;try{w2=watch(dir,{persistent:!1},(_ev,f)=>{if(f==="HEAD")read()})}catch{}}),()=>{dead=!0,w2?.close()}},[cwd]),val}var rtrunc=(s,max)=>s.length<=max?s:"\u2026"+s.slice(-(max-1));var import_react31=__toESM(require_react_production(),1);var enc,load3=()=>{if(enc!==void 0)return enc;try{enc=require_main()}catch{enc=null}return enc},warmup=()=>{queueMicrotask(load3)},hash=(s)=>{let h2=5381;for(let i=0;i<s.length;i++)h2=(h2<<5)+h2+s.charCodeAt(i)|0;return String(h2)},cache2=new Map;var roughCount=(s)=>Math.ceil(s.length/4);function count2(s){if(!s)return 0;let k2=hash(s),hit=cache2.get(k2);if(hit!==void 0)return hit;let n;try{n=load3()?.countTokens(s)??roughCount(s)}catch{n=roughCount(s)}if(cache2.size>=1024){let first=cache2.keys().next().value;if(first!==void 0)cache2.delete(first)}return cache2.set(k2,n),n}function formatTokens(n){if(!Number.isFinite(n)||n<0)return"0";if(n>=1e6){let m2=n/1e6;return m2===Math.floor(m2)?`${m2}M`:`${m2.toFixed(1)}M`}if(n>=1e4)return`${Math.round(n/1000)}K`;if(n>=1000)return`${(n/1000).toFixed(1)}K`;return String(Math.round(n))}var FILL="\u2588",EMPTY="\u2591",ramp=(ratio)=>{if(ratio>=0.9)return"error";if(ratio>=0.75)return"warning";if(ratio>=0.5)return"primary";return"muted"},centered=(s,width)=>{let pad=Math.max(0,width-s.length),left=Math.ceil(pad/2),right=pad-left;return" ".repeat(left)+s+" ".repeat(right)},formatPct=(ratio)=>{let pct=ratio*100;if(pct<10)return`${pct.toFixed(1)}%`;return`${Math.round(pct)}%`},ContextGauge=import_react31.memo((props)=>{let theme=useTheme().theme,info=props.info,used=props.usage?.context_used??info?.usage?.context_used??info?.context_used,max=props.usage?.context_max??info?.usage?.context_max??info?.context_max;if(typeof max!=="number"||max<=0)return null;if(typeof used!=="number")return null;let ratio=Math.max(0,Math.min(1,used/max)),cells=Math.max(8,props.width-2),filled=Math.round(ratio*cells),bar=FILL.repeat(filled)+EMPTY.repeat(cells-filled),color=(()=>{switch(ramp(ratio)){case"error":return theme.error;case"warning":return theme.warning;case"primary":return theme.primary;default:return theme.textMuted}})(),top=`${formatTokens(used)} / ${formatTokens(max)}`,pct=formatPct(ratio);return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(top,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:color,children:centered(`[${bar}]`,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(pct,props.width)})})})]})});var import_react32=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react32.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var WIDTH=48,PAD_L=12,INNER=WIDTH-4,trunc=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",Section=import_react33.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react33.useState(!1);return $jsxs("box",{flexDirection:"column",marginBottom:props.open?1:0,children:[$jsx("box",{height:1,onMouseDown:props.onToggle,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsx("span",{fg:hover?theme.text:theme.textMuted,children:props.open?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:props.title})}),props.hint?$jsx("span",{fg:theme.textMuted,children:` ${props.hint}`}):null]})}),props.open?$jsx("box",{flexDirection:"column",children:props.children}):null]})}),Avatar=(props)=>$jsx(AnimatedAvatar,{state:props.state,eikon:props.eikon,onHold:props.onHold},props.id),Row=(props)=>{let theme=useTheme().theme;if(props.block)return $jsxs("box",{flexDirection:"column",minHeight:2,marginBottom:1,children:[$jsx("text",{fg:theme.textMuted,children:` ${props.label}`}),$jsx("text",{fg:theme.text,wrapMode:"word",children:props.value})]});return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:` ${props.label.padEnd(PAD_L)}`}),props.strong?$jsx("span",{fg:theme.text,children:$jsx("strong",{children:trunc(props.value,INNER-PAD_L-2)})}):$jsx("span",{fg:theme.text,children:trunc(props.value,INNER-PAD_L-2)})]})})},Preview=(props)=>{let theme=useTheme().theme,meta=props.preview.eikon.meta,rows2=props.preview.rows??[{label:"Author",value:meta.author??"\u2014"},{label:"State",value:props.preview.state}],states=props.preview.states?.length?props.preview.states:void 0;return $jsxs("box",{flexDirection:"column",children:[$jsx(Row,{label:"Eikon",value:props.preview.title??meta.name,strong:!0}),props.preview.subtitle?$jsx(Row,{label:"Author",value:props.preview.subtitle}):null,props.preview.body?$jsx("box",{marginTop:1,marginBottom:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.preview.body})}):null,states?$jsx("box",{flexDirection:"row",flexWrap:"wrap",marginBottom:1,children:states.map((s,i)=>$jsx(FilterChip,{label:s,state:s===props.preview.state?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.textMuted,onMouseDown:()=>{if(props.preview.onState)props.preview.onState(s)}},s))}):null,rows2.map((r,i)=>$jsx(Row,{label:r.label,value:r.value,strong:r.strong,block:r.block},`${r.label}:${i}`))]})},Sidebar=import_react33.memo((props)=>{let theme=useTheme().theme,state=props.preview?.state??props.agentState??"idle",info=props.info,eikon=props.preview?.eikon??props.eikon,preview=!!props.preview,[mcpOpen,setMcpOpen]=import_react33.useState(!1),cwd=info?.cwd??process.cwd(),branch2=useGitBranch(cwd);return $jsxs("box",{width:WIDTH,flexDirection:"column",children:[$jsxs("box",{position:"relative",flexDirection:"column",height:24,overflow:"hidden",onMouseDown:preview?void 0:props.onAvatar,children:[$jsx(Avatar,{id:props.preview?.key,state,eikon,onHold:preview?void 0:props.onAvatarHold}),!preview&&props.cloud?$jsx("box",{position:"absolute",left:0,top:0,children:$jsx(Tail,{run:!!props.pulse})}):null]}),$jsxs("box",{padding:1,flexDirection:"column",flexGrow:1,overflow:"hidden",border:["top","left","right"],borderStyle:"double",borderColor:theme.hermAvatar,children:[props.preview?$jsx(Preview,{preview:props.preview}):$jsxs($Fragment,{children:[$jsx(Row,{label:"Title",value:props.title||"\u2014",strong:!!props.title}),$jsx(Row,{label:"Profile",value:props.profile??"default",strong:!!props.profile&&props.profile!=="default"}),$jsx(Row,{label:"Model",value:info?.model??"\u2014"}),info?.cwd?$jsx(Row,{label:"cwd",value:info.cwd}):null,branch2?$jsx(Row,{label:"Branch",value:rtrunc(branch2,INNER-PAD_L-2)}):null,(info?.mcp_servers?.length??0)>0?(()=>{let srv=info.mcp_servers,ok=srv.filter((s)=>s.connected).length;return $jsx(Section,{title:"MCP",hint:`${ok}/${srv.length} up`,open:mcpOpen,onToggle:()=>setMcpOpen((o)=>!o),children:srv.map((s)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:s.connected?theme.text:theme.textMuted,children:(s.connected?"\u25CF ":"\u25CB ")+trunc(s.name,16).padEnd(16)}),$jsx("span",{fg:theme.textMuted,children:s.connected?` ${s.transport} \xB7 ${s.tools}t`:" failed"})]})},s.name))})})():null]}),$jsx("box",{flexGrow:1}),!props.preview?$jsx(ContextGauge,{info,usage:props.usage,width:INNER}):null]})]})});var import_react45=__toESM(require_react_production(),1);var import_react44=__toESM(require_react_production(),1);var import_react42=__toESM(require_react_production(),1);var import_react34=__toESM(require_react_production(),1);var LEFT_BAR={topLeft:"",bottomLeft:"",topRight:"",bottomRight:"",horizontal:"",vertical:"\u2503",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},SIDE_PIPE={topLeft:"\u2502",bottomLeft:"\u2502",vertical:"\u2502",topRight:"\u2502",bottomRight:"\u2502",horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},CORNERS={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:" ",vertical:" ",topT:" ",bottomT:" ",leftT:" ",rightT:" ",cross:" "};import{platform}from"os";var OSC52_CAPABLE=["ghostty","kitty","WezTerm","windows-terminal","vscode"];function detect(){let env2=process.env;if(env2.CURSOR_TRACE_ID)return"cursor";if(env2.TERM==="xterm-ghostty")return"ghostty";if(env2.TERM?.includes("kitty"))return"kitty";if(env2.TERM_PROGRAM)return env2.TERM_PROGRAM;if(env2.TMUX)return"tmux";if(env2.STY)return"screen";if(env2.KITTY_WINDOW_ID)return"kitty";if(env2.WT_SESSION)return"windows-terminal";return env2.TERM??null}var terminal=detect();function supportsOsc52Clipboard(t2=terminal){return OSC52_CAPABLE.includes(t2??"")}function shouldUseNativeClipboard(env2=process.env,t2=terminal){if(env2.SSH_CONNECTION)return!1;if(env2.TMUX||env2.STY)return!0;if(!process.stdout.isTTY)return!0;return!supportsOsc52Clipboard(t2)}function writeOsc52(text3){if(!process.stdout.isTTY)return;let osc52=`\x1B]52;c;${Buffer.from(text3).toString("base64")}\x07`,seq=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${osc52}\x1B\\`:osc52;process.stdout.write(seq)}async function nativeCopy(text3){let os2=platform();if(os2==="darwin"){let proc=Bun.spawn(["pbcopy"],{stdin:"pipe"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}if(os2==="linux"){if(process.env.WAYLAND_DISPLAY)try{let proc=Bun.spawn(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}}}async function copy(text3){if(writeOsc52(text3),shouldUseNativeClipboard())await nativeCopy(text3).catch(()=>{})}function copySelection(renderer){let text3=renderer.getSelection()?.getSelectedText();if(!text3)return!1;return copy(text3).catch(()=>{}),renderer.clearSelection(),!0}var CAP2=6,ErrorBlock=import_react34.memo(({text:text3})=>{let theme=useTheme().theme,[open,setOpen]=import_react34.useState(!1),[copied,setCopied]=import_react34.useState(!1),lines3=text3.trimEnd().split(`
|
|
4091
|
-
`),head=lines3[0]||"Error",body=lines3.slice(1),over=body.length>CAP2,shown=open||!over?body:body.slice(0,CAP2);import_react34.useEffect(()=>{if(!copied)return;let t2=setTimeout(()=>setCopied(!1),1500);return()=>clearTimeout(t2)},[copied]);let doCopy=()=>{copy(text3),setCopied(!0)};return $jsxs("box",{border:["left"],borderColor:theme.error,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingTop:1,paddingBottom:1,marginTop:1,flexDirection:"column",gap:1,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("box",{flexGrow:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:"\u2717 "}),$jsx("span",{fg:theme.text,children:head})]})}),$jsx("box",{onMouseDown:doCopy,paddingX:1,children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:copied?"copied":"copy"})})]}),shown.length?$jsxs("box",{flexDirection:"column",onMouseDown:over?()=>setOpen((o)=>!o):void 0,children:[shown.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:l||" "})},i)),over?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:open?"Click to collapse":`\u2026 ${body.length-CAP2} more \u2014 click to expand`})}):null]}):null]})});var import_react35=__toESM(require_react_production(),1);import process8 from"process";import path6 from"path";import{fileURLToPath as fileURLToPath3}from"url";import childProcess3 from"child_process";import fs6,{constants as fsConstants2}from"fs/promises";import{promisify as promisify2}from"util";import childProcess2 from"child_process";import fs5,{constants as fsConstants}from"fs/promises";import process2 from"process";import os2 from"os";import fs4 from"fs";import fs3 from"fs";import fs2 from"fs";var isDockerCached;function hasDockerEnv(){try{return fs2.statSync("/.dockerenv"),!0}catch{return!1}}function hasDockerCGroup(){try{return fs2.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function isDocker(){if(isDockerCached===void 0)isDockerCached=hasDockerEnv()||hasDockerCGroup();return isDockerCached}var cachedResult,hasContainerEnv=()=>{try{return fs3.statSync("/run/.containerenv"),!0}catch{return!1}};function isInsideContainer(){if(cachedResult===void 0)cachedResult=hasContainerEnv()||isDocker();return cachedResult}var isWsl=()=>{if(process2.platform!=="linux")return!1;if(os2.release().toLowerCase().includes("microsoft")){if(isInsideContainer())return!1;return!0}try{if(fs4.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!isInsideContainer()}catch{}if(fs4.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||fs4.existsSync("/run/WSL"))return!isInsideContainer();return!1},is_wsl_default=process2.env.__IS_WSL_TEST__?isWsl:isWsl();import process3 from"process";import{Buffer as Buffer4}from"buffer";import{promisify}from"util";import childProcess from"child_process";var execFile=promisify(childProcess.execFile),powerShellPath=()=>`${process3.env.SYSTEMROOT||process3.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var executePowerShell=async(command,options={})=>{let{powerShellPath:psPath,...execFileOptions}=options,encodedCommand=executePowerShell.encodeCommand(command);return execFile(psPath??powerShellPath(),[...executePowerShell.argumentsPrefix,encodedCommand],{encoding:"utf8",...execFileOptions})};executePowerShell.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];executePowerShell.encodeCommand=(command)=>Buffer4.from(command,"utf16le").toString("base64");executePowerShell.escapeArgument=(value)=>`'${String(value).replaceAll("'","''")}'`;function parseMountPointFromConfig(content){for(let line of content.split(`
|
|
4088
|
+
`),existsSync8(dst))renameSync2(dst,old);try{renameSync2(tmp,dst)}catch(err){if(existsSync8(old))renameSync2(old,dst);throw err}if(existsSync8(old))rmSync(old,{recursive:!0,force:!0});return cleanupResolved(r),{...r,name,dir:dst,sources,n:xs.length,bytes}}catch(err){throw rmSync(tmp,{recursive:!0,force:!0}),cleanupResolved(r),err}}function dirty(dir){let mf=join7(dir,"manifest.json");if(!existsSync8(mf))return!1;let man=JSON.parse(readFileSync3(mf,"utf8"));if(!man.origin?.at)return!1;let since=Date.parse(man.origin.at);for(let e of readdirSync2(dir,{withFileTypes:!0,recursive:!0}))if(statSync(join7(e.parentPath??dir,e.name)).mtimeMs>since+2000)return!0;return!1}import{existsSync as existsSync9,lstatSync as lstatSync2,readFileSync as readFileSync4}from"fs";import{basename as basename6,dirname as dirname6,join as join8,relative as relative2,resolve as resolve7,sep}from"path";var DEFAULT_SUBMIT_REPO=process.env.EIKON_REPO??"liftaris/eikon",DEFAULT_MAX_BUNDLE_BYTES=33554432,SECRET=/(\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|id_rsa$|id_ed25519$|token|secret|credential|password)/i;var hidden=(rel)=>rel.split(/[\\/]/).some((p)=>p.startsWith(".")),secret=(rel)=>SECRET.test(rel);var posix=(s)=>s.split(sep).join("/");function contain(root,rel){if(rel.startsWith("/")||/^[A-Za-z]:[\\/]/.test(rel)||rel.split(/[\\/]/).some((p)=>p===".."))throw Error(`submission bundle path escape: ${rel}`);let abs=resolve7(root,rel),back=relative2(root,abs);if(back.startsWith("..")||back===""||resolve7(root,back)!==abs)throw Error(`submission bundle path escape: ${rel}`);return{abs,rel:posix(back)}}function add(root,rel,out,opts){let path6=contain(root,rel);if(!existsSync9(path6.abs))throw Error(`submission bundle missing source: ${path6.rel}`);if(!opts.allowHidden&&hidden(path6.rel))return;if(!opts.allowSecrets&&secret(path6.rel))return;let parts2=path6.rel.split("/"),cur=root;for(let part of parts2){cur=join8(cur,part);let st2=lstatSync2(cur);if(st2.isSymbolicLink())throw Error(`submission bundle symlink unsupported: ${path6.rel}`);if(part!==parts2.at(-1)&&!st2.isDirectory())return;if(part===parts2.at(-1)&&!st2.isFile())return}let bytes=lstatSync2(path6.abs).size;out.set(path6.rel,{path:path6.rel,abs:path6.abs,bytes})}function bundleFiles(root,packed,man,opts){let out=new Map;if(add(root,basename6(packed),out,opts),man){if(add(root,"manifest.json",out,opts),man.source)add(root,man.source,out,opts);for(let[st,v2]of Object.entries(man.states??{}))if(v2?.file)add(root,v2.file,out,opts);else throw Error(`manifest states.${st}.file required`)}for(let rel of opts.extraFiles??[])add(root,rel,out,opts);let files=[...out.values()].sort((a,b2)=>a.path.localeCompare(b2.path)),bytes=files.reduce((n,f)=>n+f.bytes,0),max=opts.maxBytes??DEFAULT_MAX_BUNDLE_BYTES;if(bytes>max)throw Error(`submission bundle too large: ${bytes} > ${max} bytes`);return files}async function previewSubmitBundle(opts){let packed=resolve7(opts.path),root=dirname6(packed),eikon;try{eikon=lint(decodeRuntimeFile(packed))}catch(err){throw Error(`invalid eikon: ${err instanceof Error?err.message:String(err)}`)}let mf=join8(root,"manifest.json"),manifest2=existsSync9(mf)?lintManifest(mf,readFileSync4(mf,"utf8")):void 0,files=bundleFiles(root,packed,manifest2,opts),catalog2=catalogEntry({name:eikon.meta.name,author:eikon.meta.author,glyph:eikon.meta.glyph,width:eikon.meta.width,height:eikon.meta.height,poster:poster(eikon),source:`${eikon.meta.name}/`,runtime_url:`${eikon.meta.name}/${eikon.meta.name}.eikon`,package_url:manifest2?`${eikon.meta.name}/manifest.json`:void 0},"https://eikon.liftaris.dev/eikons/",{allowPrivate:!0});return{root,packed,files,meta:eikon.meta,...manifest2?{manifest:manifest2}:{},catalog:catalog2}}async function gh(args,input){let p=Bun.spawn(["gh",...args],{stdin:input?new TextEncoder().encode(input):void 0,stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text(),p.exited]);if(code!==0)throw Error(`gh ${args[0]} failed: ${err.trim()||out.trim()}`);return out.trim()}async function existingSha(run,fork,branch,path6){try{let out=await run(["api","-X","GET",`repos/${fork}/contents/${path6}`,"-f",`ref=${branch}`]),json=JSON.parse(out);return typeof json.sha==="string"?json.sha:void 0}catch{return}}function githubSubmitBackend(repo=DEFAULT_SUBMIT_REPO,run=gh){return{async check(){try{return await run(["auth","status"]),{ok:!0}}catch(err){return{ok:!1,reason:err instanceof Error?err.message:String(err)}}},async create(req){let name=req.bundle.meta.name,branch=`submit/${name}`;await run(["repo","fork",repo,"--clone=false"]).catch(()=>"");let user=await run(["api","user","-q",".login"]),fork=`${user}/${repo.split("/")[1]}`,main2=await run(["api",`repos/${repo}/git/ref/heads/main`,"-q",".object.sha"]);await run(["api","-X","POST",`repos/${fork}/git/refs`,"-f",`ref=refs/heads/${branch}`,"-f",`sha=${main2}`]).catch(()=>"");for(let file of req.bundle.files){let dest=`eikons/${name}/${file.path}`,content=Buffer.from(await Bun.file(file.abs).arrayBuffer()).toString("base64"),sha=await existingSha(run,fork,branch,dest),args=["api","-X","PUT",`repos/${fork}/contents/${dest}`,"-f",`message=eikons: submit ${name}`,"-f",`branch=${branch}`,"-f",`content=${content}`];if(sha)args.push("-f",`sha=${sha}`);await run(args)}return{kind:"submitted",url:await run(["pr","create","-R",repo,"-H",`${user}:${branch}`,"-B","main","-t",req.title,"-b",req.body]),request:req}}}}var STREAM_EXT=/\.eikon$/;function readManifestEntrypoint(path6){try{let entrypoints=JSON.parse(readFileSync5(path6,"utf8")).entrypoints;if(!entrypoints||typeof entrypoints!=="object"||Array.isArray(entrypoints))return;let value=entrypoints.default;return typeof value==="string"&&STREAM_EXT.test(value)?value:void 0}catch{return}}function parseEikon(text3){let first=text3.split(`
|
|
4089
|
+
`,1)[0];if((first?JSON.parse(first):{}).type==="header"){let e2=parseLaunchStream(text3);return{meta:e2.meta,states:e2.clips,resolve:(signal)=>{try{return e2.clips.get(resolveSignal(e2,signal).clip)}catch{return}}}}let e=parse3(text3);return{meta:e.meta,states:e.clips,resolve:(signal)=>e.clips.get(signal.replace(/^state\./,""))}}function parseEikonFile(path6){return parseEikon(decodeRuntimeFile(path6))}function listEikons(dirs){return dirs.flatMap((dir)=>{let ents;try{ents=readdirSync3(dir,{recursive:!0})}catch{return[]}let paths=ents.map((e)=>join9(dir,e)),streamFiles=paths.filter((path6)=>STREAM_EXT.test(path6)),packageEntrypoints=new Map;for(let manifest2 of paths.filter((path6)=>path6.endsWith("manifest.json"))){let entrypoint=readManifestEntrypoint(manifest2);if(entrypoint){let root=dirname7(manifest2);packageEntrypoints.set(root,join9(root,entrypoint))}}let packageRootFor=(path6)=>{for(let root of packageEntrypoints.keys()){let rel=relative3(root,path6);if(rel&&!rel.startsWith("..")&&!isAbsolute2(rel))return root}return};return streamFiles.sort((a,b2)=>a.localeCompare(b2)).filter((path6)=>{let packageRoot=packageRootFor(path6);return packageRoot?path6===packageEntrypoints.get(packageRoot):!0}).map((path6)=>({path:path6,meta:peek2(resolve8(path6))})).filter((x2)=>x2.meta!==null)})}var BLANK2={fps:1,loopFrom:1,frames:[[""]]},DEFAULT_EIKON=(()=>{try{return parseEikon(default_default)}catch{return}})(),STATE_FRAMES={idle:DEFAULT_EIKON?.states.get("idle")??BLANK2,listening:DEFAULT_EIKON?.states.get("listening")??BLANK2,thinking:DEFAULT_EIKON?.states.get("thinking")??BLANK2,speaking:DEFAULT_EIKON?.states.get("speaking")??BLANK2,working:DEFAULT_EIKON?.states.get("working")??BLANK2,error:DEFAULT_EIKON?.states.get("error")??BLANK2};init_perf();var AnimatedAvatar=import_react29.memo(({state="idle",eikon,onHold})=>{let theme=useTheme().theme,[frame,setFrame]=import_react29.useState(0),timer2=import_react29.useRef(null),holdRef=import_react29.useRef(onHold);holdRef.current=onHold;let signal=`state.${state}`,clip=eikon?.resolve(signal)??eikon?.states.get(state)??STATE_FRAMES[state],{frames,fps,loopFrom}=clip,count2=frames.length,animate=usePref("animations")!==!1,targetFps=usePref("targetFps")??30,dt=1000/Math.max(1,Math.min(fps,targetFps));import_react29.useEffect(()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null;if(setFrame(0),!animate||count2<2)return;if(count("avatar:timer:start"),process.env.HERM_TEST_PERF==="1")globalThis.__hermAvatarTimerStarts=(globalThis.__hermAvatarTimerStarts??0)+1;let idx=0,tick2=()=>{if(count("avatar:tick"),idx++,idx>=count2){if(loopFrom>=count2){setFrame(count2-1),holdRef.current?.(state);return}idx=loopFrom}setFrame(idx),timer2.current=setTimeout(tick2,dt)};return timer2.current=setTimeout(tick2,dt),()=>{if(timer2.current)clearTimeout(timer2.current),timer2.current=null,count("avatar:timer:stop")}},[state,count2,loopFrom,animate,dt]);let end=mark("avatar:render"),lines3=frames[Math.min(frame,count2-1)]??[],result=$jsx("box",{flexDirection:"column",children:lines3.map((line,i)=>$jsx("text",{children:$jsx("span",{fg:theme.hermAvatar,children:line})},i))});return end(),result});var import_react30=__toESM(require_react_production(),1);import{watch}from"fs";var TIMEOUT=500;async function git(cwd,...args){let p=Bun.spawn(["git","-C",cwd,...args],{stdout:"pipe",stderr:"ignore"}),t2=setTimeout(()=>p.kill(),TIMEOUT),out=await new Response(p.stdout).text();return clearTimeout(t2),await p.exited===0?out.trim():null}async function branch(cwd){let b2=await git(cwd,"rev-parse","--abbrev-ref","HEAD");return!b2||b2==="HEAD"?null:b2}async function gitdir(cwd){return git(cwd,"rev-parse","--absolute-git-dir")}function useGitBranch(cwd){let[val,set2]=import_react30.useState(null);return import_react30.useEffect(()=>{if(!cwd){set2(null);return}let dead=!1,w2,read=()=>branch(cwd).then((b2)=>{if(!dead)set2(b2)});return read(),gitdir(cwd).then((dir)=>{if(dead||!dir)return;try{w2=watch(dir,{persistent:!1},(_ev,f)=>{if(f==="HEAD")read()})}catch{}}),()=>{dead=!0,w2?.close()}},[cwd]),val}var rtrunc=(s,max)=>s.length<=max?s:"\u2026"+s.slice(-(max-1));var import_react31=__toESM(require_react_production(),1);var enc,load3=()=>{if(enc!==void 0)return enc;try{enc=require_main()}catch{enc=null}return enc},warmup=()=>{queueMicrotask(load3)},hash=(s)=>{let h2=5381;for(let i=0;i<s.length;i++)h2=(h2<<5)+h2+s.charCodeAt(i)|0;return String(h2)},cache2=new Map;var roughCount=(s)=>Math.ceil(s.length/4);function count2(s){if(!s)return 0;let k2=hash(s),hit=cache2.get(k2);if(hit!==void 0)return hit;let n;try{n=load3()?.countTokens(s)??roughCount(s)}catch{n=roughCount(s)}if(cache2.size>=1024){let first=cache2.keys().next().value;if(first!==void 0)cache2.delete(first)}return cache2.set(k2,n),n}function formatTokens(n){if(!Number.isFinite(n)||n<0)return"0";if(n>=1e6){let m2=n/1e6;return m2===Math.floor(m2)?`${m2}M`:`${m2.toFixed(1)}M`}if(n>=1e4)return`${Math.round(n/1000)}K`;if(n>=1000)return`${(n/1000).toFixed(1)}K`;return String(Math.round(n))}var FILL="\u2588",EMPTY="\u2591",ramp=(ratio)=>{if(ratio>=0.9)return"error";if(ratio>=0.75)return"warning";if(ratio>=0.5)return"primary";return"muted"},centered=(s,width)=>{let pad=Math.max(0,width-s.length),left=Math.ceil(pad/2),right=pad-left;return" ".repeat(left)+s+" ".repeat(right)},formatPct=(ratio)=>{let pct=ratio*100;if(pct<10)return`${pct.toFixed(1)}%`;return`${Math.round(pct)}%`},ContextGauge=import_react31.memo((props)=>{let theme=useTheme().theme,info=props.info,used=props.usage?.context_used??info?.usage?.context_used??info?.context_used,max=props.usage?.context_max??info?.usage?.context_max??info?.context_max;if(typeof max!=="number"||max<=0)return null;if(typeof used!=="number")return null;let ratio=Math.max(0,Math.min(1,used/max)),cells=Math.max(8,props.width-2),filled=Math.round(ratio*cells),bar=FILL.repeat(filled)+EMPTY.repeat(cells-filled),color=(()=>{switch(ramp(ratio)){case"error":return theme.error;case"warning":return theme.warning;case"primary":return theme.primary;default:return theme.textMuted}})(),top=`${formatTokens(used)} / ${formatTokens(max)}`,pct=formatPct(ratio);return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(top,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:color,children:centered(`[${bar}]`,props.width)})})}),$jsx("box",{height:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:centered(pct,props.width)})})})]})});var WIDTH=48,PAD_L=12,INNER=WIDTH-4,trunc=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",Section=import_react32.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react32.useState(!1);return $jsxs("box",{flexDirection:"column",marginBottom:props.open?1:0,children:[$jsx("box",{height:1,onMouseDown:props.onToggle,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsx("span",{fg:hover?theme.text:theme.textMuted,children:props.open?"\u25BE ":"\u25B8 "}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:props.title})}),props.hint?$jsx("span",{fg:theme.textMuted,children:` ${props.hint}`}):null]})}),props.open?$jsx("box",{flexDirection:"column",children:props.children}):null]})}),Avatar=(props)=>$jsx(AnimatedAvatar,{state:props.state,eikon:props.eikon,onHold:props.onHold},props.id),Row=(props)=>{let theme=useTheme().theme;if(props.block)return $jsxs("box",{flexDirection:"column",minHeight:2,marginBottom:1,children:[$jsx("text",{fg:theme.textMuted,children:` ${props.label}`}),$jsx("text",{fg:theme.text,wrapMode:"word",children:props.value})]});return $jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:` ${props.label.padEnd(PAD_L)}`}),props.strong?$jsx("span",{fg:theme.text,children:$jsx("strong",{children:trunc(props.value,INNER-PAD_L-2)})}):$jsx("span",{fg:theme.text,children:trunc(props.value,INNER-PAD_L-2)})]})})},Sidebar=import_react32.memo((props)=>{let theme=useTheme().theme,state=props.agentState??"idle",info=props.info,[mcpOpen,setMcpOpen]=import_react32.useState(!1),cwd=info?.cwd??process.cwd(),branch2=useGitBranch(cwd);return $jsxs("box",{width:WIDTH,flexDirection:"column",children:[$jsxs("box",{position:"relative",flexDirection:"column",height:24,overflow:"hidden",onMouseDown:props.onAvatar,children:[$jsx(Avatar,{state,eikon:props.eikon,onHold:props.onAvatarHold}),props.cloud?$jsx("box",{position:"absolute",left:0,top:0,children:$jsx(Tail,{run:!!props.pulse})}):null]}),$jsxs("box",{padding:1,flexDirection:"column",flexGrow:1,overflow:"hidden",border:["top","left","right"],borderStyle:"double",borderColor:theme.hermAvatar,children:[$jsx(Row,{label:"Title",value:props.title||"\u2014",strong:!!props.title}),$jsx(Row,{label:"Profile",value:props.profile??"default",strong:!!props.profile&&props.profile!=="default"}),$jsx(Row,{label:"Model",value:info?.model??"\u2014"}),info?.cwd?$jsx(Row,{label:"cwd",value:info.cwd}):null,branch2?$jsx(Row,{label:"Branch",value:rtrunc(branch2,INNER-PAD_L-2)}):null,(info?.mcp_servers?.length??0)>0?(()=>{let srv=info.mcp_servers,ok=srv.filter((s)=>s.connected).length;return $jsx(Section,{title:"MCP",hint:`${ok}/${srv.length} up`,open:mcpOpen,onToggle:()=>setMcpOpen((o)=>!o),children:srv.map((s)=>$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:s.connected?theme.text:theme.textMuted,children:(s.connected?"\u25CF ":"\u25CB ")+trunc(s.name,16).padEnd(16)}),$jsx("span",{fg:theme.textMuted,children:s.connected?` ${s.transport} \xB7 ${s.tools}t`:" failed"})]})},s.name))})})():null,$jsx("box",{flexGrow:1}),$jsx(ContextGauge,{info,usage:props.usage,width:INNER})]})]})});var import_react44=__toESM(require_react_production(),1);var import_react43=__toESM(require_react_production(),1);var import_react41=__toESM(require_react_production(),1);var import_react33=__toESM(require_react_production(),1);var LEFT_BAR={topLeft:"",bottomLeft:"",topRight:"",bottomRight:"",horizontal:"",vertical:"\u2503",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},SIDE_PIPE={topLeft:"\u2502",bottomLeft:"\u2502",vertical:"\u2502",topRight:"\u2502",bottomRight:"\u2502",horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},CORNERS={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:" ",vertical:" ",topT:" ",bottomT:" ",leftT:" ",rightT:" ",cross:" "};import{platform}from"os";var OSC52_CAPABLE=["ghostty","kitty","WezTerm","windows-terminal","vscode"];function detect(){let env2=process.env;if(env2.CURSOR_TRACE_ID)return"cursor";if(env2.TERM==="xterm-ghostty")return"ghostty";if(env2.TERM?.includes("kitty"))return"kitty";if(env2.TERM_PROGRAM)return env2.TERM_PROGRAM;if(env2.TMUX)return"tmux";if(env2.STY)return"screen";if(env2.KITTY_WINDOW_ID)return"kitty";if(env2.WT_SESSION)return"windows-terminal";return env2.TERM??null}var terminal=detect();function supportsOsc52Clipboard(t2=terminal){return OSC52_CAPABLE.includes(t2??"")}function shouldUseNativeClipboard(env2=process.env,t2=terminal){if(env2.SSH_CONNECTION)return!1;if(env2.TMUX||env2.STY)return!0;if(!process.stdout.isTTY)return!0;return!supportsOsc52Clipboard(t2)}function writeOsc52(text3){if(!process.stdout.isTTY)return;let osc52=`\x1B]52;c;${Buffer.from(text3).toString("base64")}\x07`,seq=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${osc52}\x1B\\`:osc52;process.stdout.write(seq)}async function nativeCopy(text3){let os2=platform();if(os2==="darwin"){let proc=Bun.spawn(["pbcopy"],{stdin:"pipe"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}if(os2==="linux"){if(process.env.WAYLAND_DISPLAY)try{let proc=Bun.spawn(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}try{let proc=Bun.spawn(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});proc.stdin.write(text3),proc.stdin.end(),await proc.exited;return}catch{}}}async function copy(text3){if(writeOsc52(text3),shouldUseNativeClipboard())await nativeCopy(text3).catch(()=>{})}function copySelection(renderer){let text3=renderer.getSelection()?.getSelectedText();if(!text3)return!1;return copy(text3).catch(()=>{}),renderer.clearSelection(),!0}var CAP2=6,ErrorBlock=import_react33.memo(({text:text3})=>{let theme=useTheme().theme,[open,setOpen]=import_react33.useState(!1),[copied,setCopied]=import_react33.useState(!1),lines3=text3.trimEnd().split(`
|
|
4090
|
+
`),head=lines3[0]||"Error",body=lines3.slice(1),over=body.length>CAP2,shown=open||!over?body:body.slice(0,CAP2);import_react33.useEffect(()=>{if(!copied)return;let t2=setTimeout(()=>setCopied(!1),1500);return()=>clearTimeout(t2)},[copied]);let doCopy=()=>{copy(text3),setCopied(!0)};return $jsxs("box",{border:["left"],borderColor:theme.error,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingTop:1,paddingBottom:1,marginTop:1,flexDirection:"column",gap:1,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("box",{flexGrow:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.error,children:"\u2717 "}),$jsx("span",{fg:theme.text,children:head})]})}),$jsx("box",{onMouseDown:doCopy,paddingX:1,children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:copied?"copied":"copy"})})]}),shown.length?$jsxs("box",{flexDirection:"column",onMouseDown:over?()=>setOpen((o)=>!o):void 0,children:[shown.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:l||" "})},i)),over?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:open?"Click to collapse":`\u2026 ${body.length-CAP2} more \u2014 click to expand`})}):null]}):null]})});var import_react34=__toESM(require_react_production(),1);import{spawn}from"child_process";import{platform as platform3}from"os";import process8 from"process";import path6 from"path";import{fileURLToPath as fileURLToPath3}from"url";import childProcess3 from"child_process";import fs6,{constants as fsConstants2}from"fs/promises";import{promisify as promisify2}from"util";import childProcess2 from"child_process";import fs5,{constants as fsConstants}from"fs/promises";import process2 from"process";import os2 from"os";import fs4 from"fs";import fs3 from"fs";import fs2 from"fs";var isDockerCached;function hasDockerEnv(){try{return fs2.statSync("/.dockerenv"),!0}catch{return!1}}function hasDockerCGroup(){try{return fs2.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function isDocker(){if(isDockerCached===void 0)isDockerCached=hasDockerEnv()||hasDockerCGroup();return isDockerCached}var cachedResult,hasContainerEnv=()=>{try{return fs3.statSync("/run/.containerenv"),!0}catch{return!1}};function isInsideContainer(){if(cachedResult===void 0)cachedResult=hasContainerEnv()||isDocker();return cachedResult}var isWsl=()=>{if(process2.platform!=="linux")return!1;if(os2.release().toLowerCase().includes("microsoft")){if(isInsideContainer())return!1;return!0}try{if(fs4.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!isInsideContainer()}catch{}if(fs4.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||fs4.existsSync("/run/WSL"))return!isInsideContainer();return!1},is_wsl_default=process2.env.__IS_WSL_TEST__?isWsl:isWsl();import process3 from"process";import{Buffer as Buffer4}from"buffer";import{promisify}from"util";import childProcess from"child_process";var execFile=promisify(childProcess.execFile),powerShellPath=()=>`${process3.env.SYSTEMROOT||process3.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var executePowerShell=async(command,options={})=>{let{powerShellPath:psPath,...execFileOptions}=options,encodedCommand=executePowerShell.encodeCommand(command);return execFile(psPath??powerShellPath(),[...executePowerShell.argumentsPrefix,encodedCommand],{encoding:"utf8",...execFileOptions})};executePowerShell.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];executePowerShell.encodeCommand=(command)=>Buffer4.from(command,"utf16le").toString("base64");executePowerShell.escapeArgument=(value)=>`'${String(value).replaceAll("'","''")}'`;function parseMountPointFromConfig(content){for(let line of content.split(`
|
|
4092
4091
|
`)){if(/^\s*#/.test(line))continue;let match2=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);if(!match2)continue;return match2.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var execFile2=promisify2(childProcess2.execFile),wslDrivesMountPoint=(()=>{let mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath="/etc/wsl.conf",isConfigFileExists=!1;try{await fs5.access(configFilePath,fsConstants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return"/mnt/";let configContent=await fs5.readFile(configFilePath,{encoding:"utf8"}),parsedMountPoint=parseMountPointFromConfig(configContent);if(parsedMountPoint===void 0)return"/mnt/";return mountPoint=parsedMountPoint,mountPoint=mountPoint.endsWith("/")?mountPoint:`${mountPoint}/`,mountPoint}})(),powerShellPathFromWsl=async()=>{return`${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},powerShellPath2=is_wsl_default?powerShellPathFromWsl:powerShellPath,canAccessPowerShellPromise,canAccessPowerShell=async()=>{return canAccessPowerShellPromise??=(async()=>{try{let psPath=await powerShellPath2();return await fs5.access(psPath,fsConstants.X_OK),!0}catch{return!1}})(),canAccessPowerShellPromise},wslDefaultBrowser=async()=>{let psPath=await powerShellPath2(),command=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout}=await executePowerShell(command,{powerShellPath:psPath});return stdout.trim()},convertWslPathToWindows=async(path6)=>{if(/^[a-z]+:\/\//i.test(path6))return path6;try{let{stdout}=await execFile2("wslpath",["-aw",path6],{encoding:"utf8"});return stdout.trim()}catch{return path6}};function defineLazyProperty(object,propertyName,valueGetter){let define=(value)=>Object.defineProperty(object,propertyName,{value,enumerable:!0,writable:!0});return Object.defineProperty(object,propertyName,{configurable:!0,enumerable:!0,get(){let result=valueGetter();return define(result),result},set(value){define(value)}}),object}import{promisify as promisify6}from"util";import process6 from"process";import{execFile as execFile6}from"child_process";import{promisify as promisify3}from"util";import process4 from"process";import{execFile as execFile3}from"child_process";var execFileAsync=promisify3(execFile3);async function defaultBrowserId(){if(process4.platform!=="darwin")throw Error("macOS only");let{stdout}=await execFileAsync("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),browserId=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id??"com.apple.Safari";if(browserId==="com.apple.safari")return"com.apple.Safari";return browserId}import process5 from"process";import{promisify as promisify4}from"util";import{execFile as execFile4,execFileSync}from"child_process";var execFileAsync2=promisify4(execFile4);async function runAppleScript(script,{humanReadableOutput=!0,signal}={}){if(process5.platform!=="darwin")throw Error("macOS only");let outputArguments=humanReadableOutput?[]:["-ss"],execOptions={};if(signal)execOptions.signal=signal;let{stdout}=await execFileAsync2("osascript",["-e",script,outputArguments],execOptions);return stdout.trim()}async function bundleName(bundleId){return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
|
|
4093
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as promisify5}from"util";import{execFile as execFile5}from"child_process";var execFileAsync3=promisify5(execFile5),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds));class UnknownBrowserError extends Error{}async function defaultBrowser(_execFileAsync=execFileAsync3){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match2=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match2)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match2.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}var execFileAsync4=promisify6(execFile6),titleize=(string)=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(x2)=>x2.toUpperCase());async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync4("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw Error("Only macOS, Linux, and Windows are supported")}import process7 from"process";var isInSsh=Boolean(process7.env.SSH_CONNECTION||process7.env.SSH_CLIENT||process7.env.SSH_TTY),is_in_ssh_default=isInSsh;var fallbackAttemptSymbol=Symbol("fallbackAttempt"),__dirname3=import.meta.url?path6.dirname(fileURLToPath3(import.meta.url)):"",localXdgOpenPath=path6.join(__dirname3,"xdg-open"),{platform:platform2,arch}=process8,tryEachApp=async(apps,opener)=>{if(apps.length===0)return;let errors=[];for(let app of apps)try{return await opener(app)}catch(error){errors.push(error)}throw AggregateError(errors,"Failed to open in all supported apps")},baseOpen=async(options)=>{options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options};let isFallbackAttempt=options[fallbackAttemptSymbol]===!0;if(delete options[fallbackAttemptSymbol],Array.isArray(options.app))return tryEachApp(options.app,(singleApp)=>baseOpen({...options,app:singleApp,[fallbackAttemptSymbol]:!0}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return tryEachApp(app,(appName)=>baseOpen({...options,app:{name:appName,arguments:appArguments},[fallbackAttemptSymbol]:!0}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser;if(is_wsl_default){let progId=await wslDefaultBrowser();browser=_windowsBrowserProgIdMap.get(progId)??{}}else browser=await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id.toLowerCase()];if(app==="browserPrivate"){if(browserName==="safari")throw Error("Safari doesn't support opening in private mode via command line");appArguments.push(flags[browserName])}return baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={},shouldUseWindowsInWsl=!1;if(is_wsl_default&&!isInsideContainer()&&!is_in_ssh_default&&!app)shouldUseWindowsInWsl=await canAccessPowerShell();if(platform2==="darwin"){if(command="open",options.wait)cliArguments.push("--wait-apps");if(options.background)cliArguments.push("--background");if(options.newInstance)cliArguments.push("--new");if(app)cliArguments.push("-a",app)}else if(platform2==="win32"||shouldUseWindowsInWsl){if(command=await powerShellPath2(),cliArguments.push(...executePowerShell.argumentsPrefix),!is_wsl_default)childProcessOptions.windowsVerbatimArguments=!0;if(is_wsl_default&&options.target)options.target=await convertWslPathToWindows(options.target);let encodedArguments=["$ProgressPreference = 'SilentlyContinue';","Start"];if(options.wait)encodedArguments.push("-Wait");if(app){if(encodedArguments.push(executePowerShell.escapeArgument(app)),options.target)appArguments.push(options.target)}else if(options.target)encodedArguments.push(executePowerShell.escapeArgument(options.target));if(appArguments.length>0)appArguments=appArguments.map((argument)=>executePowerShell.escapeArgument(argument)),encodedArguments.push("-ArgumentList",appArguments.join(","));if(options.target=executePowerShell.encodeCommand(encodedArguments.join(" ")),!options.wait)childProcessOptions.stdio="ignore"}else{if(app)command=app;else{let isBundled=!__dirname3||__dirname3==="/",exeLocalXdgOpen=!1;try{await fs6.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process8.versions.electron??(platform2==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}if(appArguments.length>0)cliArguments.push(...appArguments);if(!options.wait)childProcessOptions.stdio="ignore",childProcessOptions.detached=!0}if(platform2==="darwin"&&appArguments.length>0)cliArguments.push("--args",...appArguments);if(options.target)cliArguments.push(options.target);let subprocess=childProcess3.spawn(command,cliArguments,childProcessOptions);if(options.wait)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("close",(exitCode)=>{if(!options.allowNonzeroExitCode&&exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}resolve4(subprocess)})});if(isFallbackAttempt)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.once("close",(exitCode)=>{if(subprocess.off("error",reject),exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}subprocess.unref(),resolve4(subprocess)})})});return subprocess.unref(),new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.off("error",reject),resolve4(subprocess)})})},open=(target,options)=>{if(typeof target!=="string")throw TypeError("Expected a `target`");return baseOpen({...options,target})};function detectArchBinary(binary){if(typeof binary==="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform2]:platformBinary},{wsl}={}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw Error(`${platform2} is not supported`);return detectArchBinary(platformBinary)}var apps={browser:"browser",browserPrivate:"browserPrivate"};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"safari",()=>detectPlatformBinary({darwin:"Safari"}));var open_default=open;function openFile(path7){open_default(path7).catch(()=>{})}var MEDIA_LINE_RE=/^\s*[`"']?MEDIA:\s*(\S+?)[`"']?\s*$/,IMAGE_EXT=new Set(["png","jpg","jpeg","gif","webp","svg","bmp"]),AUDIO_EXT=new Set(["mp3","wav","ogg","m4a","flac","opus"]),VIDEO_EXT=new Set(["mp4","webm","mov","mkv"]),IMG_RE=/!\[[^\]\n]*\]\(([^)\s]+)(?:\s+[^)]*)?\)/g;function classify(path7){if(/^https?:\/\//i.test(path7))return"url";let ext=path7.split(".").pop()?.toLowerCase()??"";if(IMAGE_EXT.has(ext))return"img";if(AUDIO_EXT.has(ext))return"audio";if(VIDEO_EXT.has(ext))return"video";return"file"}var basename7=(p)=>p.split(/[/\\]/).pop()||p;function splitContent(text3){if(!text3.includes("MEDIA:")&&!text3.includes("```")&&!text3.includes("~~~")&&!text3.includes("!["))return[{md:text3}];let out=[],buf=[],fence=null,flush=()=>{if(buf.length)out.push({md:buf.join(`
|
|
4092
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as promisify5}from"util";import{execFile as execFile5}from"child_process";var execFileAsync3=promisify5(execFile5),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds));class UnknownBrowserError extends Error{}async function defaultBrowser(_execFileAsync=execFileAsync3){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match2=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match2)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match2.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}var execFileAsync4=promisify6(execFile6),titleize=(string)=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(x2)=>x2.toUpperCase());async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync4("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw Error("Only macOS, Linux, and Windows are supported")}import process7 from"process";var isInSsh=Boolean(process7.env.SSH_CONNECTION||process7.env.SSH_CLIENT||process7.env.SSH_TTY),is_in_ssh_default=isInSsh;var fallbackAttemptSymbol=Symbol("fallbackAttempt"),__dirname3=import.meta.url?path6.dirname(fileURLToPath3(import.meta.url)):"",localXdgOpenPath=path6.join(__dirname3,"xdg-open"),{platform:platform2,arch}=process8,tryEachApp=async(apps,opener)=>{if(apps.length===0)return;let errors=[];for(let app of apps)try{return await opener(app)}catch(error){errors.push(error)}throw AggregateError(errors,"Failed to open in all supported apps")},baseOpen=async(options)=>{options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options};let isFallbackAttempt=options[fallbackAttemptSymbol]===!0;if(delete options[fallbackAttemptSymbol],Array.isArray(options.app))return tryEachApp(options.app,(singleApp)=>baseOpen({...options,app:singleApp,[fallbackAttemptSymbol]:!0}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return tryEachApp(app,(appName)=>baseOpen({...options,app:{name:appName,arguments:appArguments},[fallbackAttemptSymbol]:!0}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser;if(is_wsl_default){let progId=await wslDefaultBrowser();browser=_windowsBrowserProgIdMap.get(progId)??{}}else browser=await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id.toLowerCase()];if(app==="browserPrivate"){if(browserName==="safari")throw Error("Safari doesn't support opening in private mode via command line");appArguments.push(flags[browserName])}return baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={},shouldUseWindowsInWsl=!1;if(is_wsl_default&&!isInsideContainer()&&!is_in_ssh_default&&!app)shouldUseWindowsInWsl=await canAccessPowerShell();if(platform2==="darwin"){if(command="open",options.wait)cliArguments.push("--wait-apps");if(options.background)cliArguments.push("--background");if(options.newInstance)cliArguments.push("--new");if(app)cliArguments.push("-a",app)}else if(platform2==="win32"||shouldUseWindowsInWsl){if(command=await powerShellPath2(),cliArguments.push(...executePowerShell.argumentsPrefix),!is_wsl_default)childProcessOptions.windowsVerbatimArguments=!0;if(is_wsl_default&&options.target)options.target=await convertWslPathToWindows(options.target);let encodedArguments=["$ProgressPreference = 'SilentlyContinue';","Start"];if(options.wait)encodedArguments.push("-Wait");if(app){if(encodedArguments.push(executePowerShell.escapeArgument(app)),options.target)appArguments.push(options.target)}else if(options.target)encodedArguments.push(executePowerShell.escapeArgument(options.target));if(appArguments.length>0)appArguments=appArguments.map((argument)=>executePowerShell.escapeArgument(argument)),encodedArguments.push("-ArgumentList",appArguments.join(","));if(options.target=executePowerShell.encodeCommand(encodedArguments.join(" ")),!options.wait)childProcessOptions.stdio="ignore"}else{if(app)command=app;else{let isBundled=!__dirname3||__dirname3==="/",exeLocalXdgOpen=!1;try{await fs6.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process8.versions.electron??(platform2==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}if(appArguments.length>0)cliArguments.push(...appArguments);if(!options.wait)childProcessOptions.stdio="ignore",childProcessOptions.detached=!0}if(platform2==="darwin"&&appArguments.length>0)cliArguments.push("--args",...appArguments);if(options.target)cliArguments.push(options.target);let subprocess=childProcess3.spawn(command,cliArguments,childProcessOptions);if(options.wait)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("close",(exitCode)=>{if(!options.allowNonzeroExitCode&&exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}resolve4(subprocess)})});if(isFallbackAttempt)return new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.once("close",(exitCode)=>{if(subprocess.off("error",reject),exitCode!==0){reject(Error(`Exited with code ${exitCode}`));return}subprocess.unref(),resolve4(subprocess)})})});return subprocess.unref(),new Promise((resolve4,reject)=>{subprocess.once("error",reject),subprocess.once("spawn",()=>{subprocess.off("error",reject),resolve4(subprocess)})})},open=(target,options)=>{if(typeof target!=="string")throw TypeError("Expected a `target`");return baseOpen({...options,target})};function detectArchBinary(binary){if(typeof binary==="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform2]:platformBinary},{wsl}={}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw Error(`${platform2} is not supported`);return detectArchBinary(platformBinary)}var apps={browser:"browser",browserPrivate:"browserPrivate"};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"safari",()=>detectPlatformBinary({darwin:"Safari"}));var open_default=open;function openFile(path7){open_default(path7).catch(()=>{})}function openUrl(raw,deps={}){let url2=parseSafeUrl(raw);if(!url2)return!1;let spawnFn=deps.spawn??spawn,id=deps.platform?.()??platform3(),cmd=openCommand(id);if(!cmd)return!1;let child;try{child=spawnFn(cmd.command,[...cmd.args,url2.toString()],{detached:!0,stdio:"ignore"})}catch{return!1}return child.once("error",()=>{}),child.unref(),!0}function parseSafeUrl(value){if(!value||typeof value!=="string")return null;let url2;try{url2=new URL(value)}catch{return null}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return null;if(!url2.hostname.trim())return null;return url2}function openCommand(id){if(id==="darwin")return{command:"open",args:[]};if(id==="win32")return{command:"explorer.exe",args:[]};if(new Set(["linux","freebsd","openbsd","netbsd","dragonfly"]).has(id))return{command:"xdg-open",args:[]};return null}var MEDIA_LINE_RE=/^\s*[`"']?MEDIA:\s*(\S+?)[`"']?\s*$/,IMAGE_EXT=new Set(["png","jpg","jpeg","gif","webp","svg","bmp"]),AUDIO_EXT=new Set(["mp3","wav","ogg","m4a","flac","opus"]),VIDEO_EXT=new Set(["mp4","webm","mov","mkv"]),IMG_RE=/!\[[^\]\n]*\]\(([^)\s]+)(?:\s+[^)]*)?\)/g;function classify(path7){if(/^https?:\/\//i.test(path7))return"url";let ext=path7.split(".").pop()?.toLowerCase()??"";if(IMAGE_EXT.has(ext))return"img";if(AUDIO_EXT.has(ext))return"audio";if(VIDEO_EXT.has(ext))return"video";return"file"}var basename7=(p)=>p.split(/[/\\]/).pop()||p;function splitContent(text3){if(!text3.includes("MEDIA:")&&!text3.includes("```")&&!text3.includes("~~~")&&!text3.includes("!["))return[{md:text3}];let out=[],buf=[],fence=null,flush=()=>{if(buf.length)out.push({md:buf.join(`
|
|
4094
4093
|
`)});buf=[]};for(let line of text3.split(`
|
|
4095
4094
|
`)){let f=line.match(/^\s*(`{3,}|~{3,})\s*(\S*)/);if(f){if(fence&&f[1][0]===fence.mark[0]&&f[1].length>=fence.mark.length){out.push({code:fence.body.join(`
|
|
4096
4095
|
`),lang:fence.lang||void 0}),fence=null;continue}if(!fence){flush(),fence={mark:f[1],lang:f[2],body:[]};continue}}if(fence){fence.body.push(line);continue}let m2=line.match(MEDIA_LINE_RE)?.[1];if(m2){flush(),out.push({media:m2});continue}let at=0,hit=!1;for(let img of line.matchAll(IMG_RE)){let path7=img[1];if(classify(path7)!=="img")continue;if(!hit)flush();if(img.index>at)out.push({md:line.slice(at,img.index)});out.push({media:path7}),at=img.index+img[0].length,hit=!0}if(hit){if(at<line.length)out.push({md:line.slice(at)});continue}buf.push(line)}if(fence){let tail=[fence.mark+(fence.lang??""),...fence.body].join(`
|
|
4097
4096
|
`),last=out[out.length-1];if(last&&"md"in last)last.md+=`
|
|
4098
|
-
`+tail;else buf.push(tail)}return flush(),out}var MediaChip=
|
|
4099
|
-
`).length,onCopy=()=>{copy(props.code),toast.show({variant:"success",message:`Copied ${lines3} line${lines3===1?"":"s"}`})};return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsxs("box",{flexDirection:"row",height:1,backgroundColor:theme.backgroundElement,onMouseDown:onCopy,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:[$jsx("box",{flexGrow:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.lang||"text"})}),$jsx("box",{paddingRight:1,children:$jsx("text",{fg:hover?theme.accent:theme.textMuted,children:hover?"\u29C9 copy":`${lines3} ln`})})]}),$jsx("box",{paddingX:1,paddingY:ft?0:1,children:ft?$jsx("code",{content:props.code,filetype:ft,syntaxStyle,fg:theme.text,wrapMode:"none",streaming:props.streaming}):$jsx("text",{fg:theme.text,children:props.code})})]})});var
|
|
4097
|
+
`+tail;else buf.push(tail)}return flush(),out}var MediaChip=import_react34.memo((props)=>{let theme=useTheme().theme,[hover,setHover]=import_react34.useState(!1),kind=classify(props.path),badge={img:theme.accent,audio:theme.warning,video:theme.info,url:theme.primary,file:theme.secondary}[kind],click=props.onMouseDown??((e)=>{e.stopPropagation(),openFile(props.path)});return $jsx("box",{flexDirection:"row",height:1,onMouseDown:click,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:$jsxs("text",{children:[$jsxs("span",{bg:badge,fg:theme.background,children:[" ",kind," "]}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.text,attributes:hover?TextAttributes.UNDERLINE:TextAttributes.NONE,children:[" ",basename7(props.path)," "]})]})})});var import_react36=__toESM(require_react_production(),1);var import_react35=__toESM(require_react_production(),1);var Ctx3=import_react35.createContext(null),DEFAULT_DURATION=3000,ToastProvider=({children})=>{let[items,setItems]=import_react35.useState([]),counter=import_react35.useRef(0),timers=import_react35.useRef(new Map);import_react35.useEffect(()=>()=>{for(let t2 of timers.current.values())clearTimeout(t2)},[]);let show=import_react35.useCallback((opts)=>{let id=++counter.current;setItems((prev)=>{let drop=opts.key?prev.filter((t2)=>t2.key===opts.key):[];for(let item of drop){let t2=timers.current.get(item.id);if(t2)clearTimeout(t2);timers.current.delete(item.id)}return[...opts.key?prev.filter((t2)=>t2.key!==opts.key):prev,{...opts,id}]});let dur2=opts.duration??DEFAULT_DURATION;if(dur2===null)return;timers.current.set(id,setTimeout(()=>{timers.current.delete(id),setItems((prev)=>prev.filter((t2)=>t2.id!==id))},dur2))},[]),clear=import_react35.useCallback((key3)=>{setItems((prev)=>{for(let item of prev){if(item.key!==key3)continue;let t2=timers.current.get(item.id);if(t2)clearTimeout(t2);timers.current.delete(item.id)}return prev.filter((t2)=>t2.key!==key3)})},[]),error=import_react35.useCallback((err)=>{show({variant:"error",title:"Error",message:err.message})},[show]),value=import_react35.useMemo(()=>({show,clear,error}),[show,clear,error]);return $jsxs(Ctx3.Provider,{value,children:[children,items.length>0?$jsx(ToastOverlay,{items}):null]})},ToastOverlay=({items})=>{let theme=useTheme().theme,color=(variant)=>{switch(variant){case"error":return theme.error;case"warning":return theme.warning;case"success":return theme.success;default:return theme.info}};return $jsx("box",{position:"absolute",top:2,right:2,flexDirection:"column",gap:1,zIndex:200,maxWidth:60,children:items.map((item)=>$jsxs("box",{backgroundColor:theme.backgroundPanel,border:["left"],borderStyle:"single",borderColor:color(item.variant),paddingLeft:1,paddingRight:1,flexDirection:"column",children:[item.title?$jsx("text",{fg:theme.text,children:$jsx("strong",{children:item.title})}):null,$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:item.message}),item.action?$jsx("box",{height:1,marginTop:0,onMouseDown:item.action.run,children:$jsx("text",{fg:color(item.variant),children:$jsx("u",{children:item.action.label})})}):null]},item.id))})},useToast=makeUse(Ctx3,"useToast");var FILETYPE={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rb:"ruby",rs:"rust",sh:"bash",shell:"bash",yml:"yaml",md:"markdown"},CodeBlock=import_react36.memo((props)=>{let{theme,syntaxStyle}=useTheme(),toast=useToast(),[hover,setHover]=import_react36.useState(!1),ft=props.lang?FILETYPE[props.lang.toLowerCase()]??props.lang.toLowerCase():void 0,lines3=props.code.split(`
|
|
4098
|
+
`).length,onCopy=()=>{copy(props.code),toast.show({variant:"success",message:`Copied ${lines3} line${lines3===1?"":"s"}`})};return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsxs("box",{flexDirection:"row",height:1,backgroundColor:theme.backgroundElement,onMouseDown:onCopy,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),children:[$jsx("box",{flexGrow:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.lang||"text"})}),$jsx("box",{paddingRight:1,children:$jsx("text",{fg:hover?theme.accent:theme.textMuted,children:hover?"\u29C9 copy":`${lines3} ln`})})]}),$jsx("box",{paddingX:1,paddingY:ft?0:1,children:ft?$jsx("code",{content:props.code,filetype:ft,syntaxStyle,fg:theme.text,wrapMode:"none",streaming:props.streaming}):$jsx("text",{fg:theme.text,children:props.code})})]})});var import_react37=__toESM(require_react_production(),1);var PATH_KEY=/"(?:path|file_path|filename|target|file)"\s*:\s*"((?:\\.|[^"\\])*)"/,DIFF_HEAD_ARROW=/(?:^|\s)a\/+\S.*?\s*\u2192\s*b\/+(\S.+?)\s*$/m,DIFF_HEAD_NEW=/^\+\+\+ b?\/+(\S.*?)\s*$/m,DIFF_HEAD_OLD=/^--- a?\/+(\S.*?)\s*$/m;function pathFor(t2){let args=t2.args;if(args&&/^\s*\{/.test(args)){let m2=sanitize(args).match(PATH_KEY);if(m2)return m2[1]}let sources=[t2.diff,t2.preview].filter((s)=>!!s);for(let s of sources){let c=sanitize(s),m2=c.match(DIFF_HEAD_ARROW)||c.match(DIFF_HEAD_NEW)||c.match(DIFF_HEAD_OLD);if(m2)return m2[1]}return sanitize(t2.preview??t2.name)}var STRIPS=[/^\s*\u250A.*$/,/^\s*[+-]\d+\s*\/\s*[-+]\d+\s*$/,/^\s*\u2026/,/a\/+\S.*?\s*\u2192\s*b\/+\S/];function sanitizeDiff(s){return sanitize(s).split(`
|
|
4100
4099
|
`).filter((l)=>!STRIPS.some((re2)=>re2.test(l))).join(`
|
|
4101
4100
|
`)}var base=(p)=>p.split(/[\\/]/).filter(Boolean).pop()??p,parent=(p)=>{let parts2=p.split(/[\\/]/).filter(Boolean);return parts2.length>=2?parts2[parts2.length-2]:""},trunc2=(s,n)=>s.length<=n?s:"\u2026"+s.slice(-(n-1));function buildTabs(tools){let raw=tools.flatMap((t2)=>{let rawDiff=t2.diff??(isDiff(t2.result)?t2.result:void 0);if(!rawDiff)return[];return[{tool:t2,path:pathFor(t2),diff:sanitizeDiff(rawDiff)}]}),counts=new Map;return raw.forEach((r)=>counts.set(base(r.path),(counts.get(base(r.path))??0)+1)),raw.map(({tool,path:path7,diff})=>{let b2=base(path7),dup=(counts.get(b2)??0)>1&&parent(path7),label=trunc2(dup?`${parent(path7)}/${b2}`:b2,24),lines3=diff.split(`
|
|
4102
|
-
`),add2=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add:add2,del}})}var DiffTabs=import_react38.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react38.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react38.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react39=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,focused:!0,flexGrow:1,textColor:theme.backgroundElement,cursorColor:theme.accent,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{position:"absolute",left:2,top:0,height:1,children:$jsx("text",{fg:theme.text,bg:theme.backgroundElement,children:"\u2022".repeat(props.value.length)})})]})};function digit(name){let n=parseInt(name,10);return Number.isFinite(n)?n:null}var Frame=(p)=>{let theme=useTheme().theme;return $jsx("box",{flexDirection:"column",border:["left"],borderColor:p.tint,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,marginBottom:1,children:p.children})},Pill=(p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,paddingX:1,backgroundColor:p.on?theme.primary:void 0,onMouseDown:p.onPick,children:$jsxs("text",{children:[$jsxs("span",{fg:p.on?theme.background:theme.textMuted,children:[p.hot," "]}),$jsx("span",{fg:p.on?theme.background:theme.text,children:p.label})]})})},CHOICES=["once","session","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react39.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react39.useState(0),[steering,setSteering]=import_react39.useState(!1),[custom,setCustom]=import_react39.useState(""),[note,setNote]=import_react39.useState(""),done=import_react39.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react39.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react39.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react39.useState(0),[typing,setTyping]=import_react39.useState(choices.length===0),[custom,setCustom]=import_react39.useState(""),done=import_react39.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react39.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react39.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react39.useState(""),done=import_react39.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react39.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.name==="escape")return go(""),!0;return!1}}),[]),$jsx(Frame,{tint:theme.warning,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})}),$jsx("text",{fg:theme.text,children:p.note}),$jsx("box",{height:1}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react39.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react39.memo(import_react39.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react40=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync2}from"fs";function parseChafaLine(line){let out=[],fg2=null,bg2=null,reverse2=!1,i=0,N2=line.length;while(i<N2){if(line.charCodeAt(i)===27&&line.charCodeAt(i+1)===91){let end=line.indexOf("m",i+2);if(end<0){i=N2;break}let params=line.slice(i+2,end).split(";").map((x2)=>parseInt(x2,10)||0),p=0;while(p<params.length){let n=params[p];if(n===0){fg2=null,bg2=null,reverse2=!1,p++;continue}if(n===7){reverse2=!0,p++;continue}if(n===27){reverse2=!1,p++;continue}if(n===38&¶ms[p+1]===2){fg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===48&¶ms[p+1]===2){bg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===39){fg2=null,p++;continue}if(n===49){bg2=null,p++;continue}p++}i=end+1;continue}let cp=line.codePointAt(i),ch=String.fromCodePoint(cp);i+=ch.length;let efg=reverse2?bg2:fg2,ebg=reverse2?fg2:bg2;out.push({ch,fg:efg,bg:ebg})}return out}function parseChafa(text3){return text3.split(`
|
|
4103
|
-
`).filter((s)=>s.length>0).map(parseChafaLine)}function hex(c){if(!c)return;return`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`}var CHAFA_PATHS=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa","/home/linuxbrew/.linuxbrew/bin/chafa"],cachedBin=void 0;function chafaBin(){if(cachedBin!==void 0)return cachedBin;for(let p of CHAFA_PATHS)if(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(full)?full:null}var CACHE=new Map,CACHE_CAP=50;function cacheGet(k2){let v2=CACHE.get(k2);if(!v2)return;return CACHE.delete(k2),CACHE.set(k2,v2),v2}function cachePut(k2,v2){if(CACHE.size>=CACHE_CAP)CACHE.delete(CACHE.keys().next().value);CACHE.set(k2,v2)}function renderChafa(path7,width,height){let bin=chafaBin();if(!bin)return{err:"chafa not installed"};let full=resolveImage(path7);if(!full)return{err:`not found: ${path7}`};let mtime=0;try{mtime=statSync2(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);if(cached2)return{rows:cached2};let r=spawnSync(bin,[`--size=${width}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8",timeout:5000});if(r.error)return{err:r.error.message};if(r.status!==0)return{err:(r.stderr||`chafa exit ${r.status}`).trim()};let rows2=parseChafa(r.stdout);return cachePut(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react40.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react40.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react40.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,onMouseDown:(e)=>{e.stopPropagation(),openFile(path7)},children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.accent,children:"\u25C9 "}),$jsx("span",{fg:theme.text,children:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react41=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react41.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react41.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react41.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react42.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react42.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react42.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react42.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react42.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react42.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),rule=import_react42.useMemo(()=>mix(theme.background,theme.backgroundElement),[theme.background,theme.backgroundElement]),segs=import_react42.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:rule}),$jsx("box",{backgroundColor:hover?rule:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:message.parts.map((p,i)=>{let seg=segs[i];if(!seg)return null;let k2=p.key??i;return seg.map((s,j2)=>{if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang},`${k2}-c${j2}`);return $jsx("text",{fg:theme.text,wrapMode:"word",children:s.md},`${k2}-${j2}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:rule})]})}),AssistantMessage=import_react42.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react42.useState(!1),click=useClick(onPick&&(()=>onPick(message))),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react42.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsx("box",{width:3,flexShrink:0,backgroundColor:hover?theme.backgroundElement:void 0}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]})]})});var import_react43=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react43.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react43.useState(0);return import_react43.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react44.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react44.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant",firstUser=messages.findIndex((m2)=>m2.role==="user");return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsxs("box",{flexDirection:"column",children:[msg.role==="user"&&i>firstUser?$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"\u2500\u2500\u2500"})}):null,$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})]},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react45.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join10}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join10(homedir4(),".hermes"),entry=()=>{let js=join10(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn=()=>{if(state.w)return state.w;let w2=new Worker(entry());return w2.onmessage=(e)=>{let r=e.data;state.pending.get(r.id)?.(r),state.pending.delete(r.id)},w2.onerror=(ev)=>{let err=`io worker: ${ev.message}`;for(let res of state.pending.values())res({id:-1,ok:!1,err});state.pending.clear()},state.w=w2},call=(fn,args)=>{if(INLINE)return state.inline??=Promise.resolve().then(() => (init_fns(),exports_fns)).then((m2)=>m2.FNS),state.inline.then((f)=>f[fn](...args));return new Promise((resolve4,reject)=>{let id=++state.seq;state.pending.set(id,(r)=>r.ok?resolve4(r.v):reject(Error(r.err))),spawn().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react46=__toESM(require_react_production(),1);var Ctx5=import_react46.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react46.useState([]),gate=import_react46.useRef(!1),gen=import_react46.useRef(0),prev=import_react46.useRef(null),refocus=import_react46.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react46.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react46.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react46.useCallback(()=>gate.current,[]),onError=import_react46.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react46.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react46.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react46.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react48=__toESM(require_react_production(),1);var HintBar=import_react48.memo((props)=>{let theme=useTheme().theme,text3=props.pairs?props.pairs.map((p)=>`[${p[0]}] ${p[1]}`).join(" ")+(props.suffix?` \xB7 ${props.suffix}`:""):props.raw??"";return $jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react49=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react49.useRef(null),node=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react49.useState(!1);import_react49.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.length<=cur){tn.scrollX=0;return}tn.scrollX=(tn.scrollX+1)%period},p.speed??180)},p.hold??600);return()=>{if(clearTimeout(hold),id)clearInterval(id);if(node.current)node.current.scrollX=0}},[animate,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react50=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react50.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react50.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(c)=>c==null?"\u2014":`$${c.toFixed(2)}`,clock=(d2)=>d2.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:h12()}),stamp=(ts)=>{let d2=new Date(ts*1000);return d2.toDateString()===new Date().toDateString()?clock(d2):d2.toLocaleDateString(void 0,{month:"short",day:"numeric"})},rel=(ts)=>{let s=Math.floor(Date.now()/1000-ts);if(s<60)return"just now";if(s<3600)return`${Math.floor(s/60)}m ago`;if(s<86400)return`${Math.floor(s/3600)}h ago`;return`${Math.floor(s/86400)}d ago`},ago=(ts)=>abs()?stamp(ts):rel(ts),until=(ts)=>{if(abs())return ts<=Date.now()/1000?"due":stamp(ts);let s=Math.floor(ts-Date.now()/1000);if(s<=0)return"due";if(s<60)return`in ${s}s`;if(s<3600)return`in ${Math.floor(s/60)}m`;if(s<86400)return`in ${Math.floor(s/3600)}h`;return`in ${Math.floor(s/86400)}d`},when=(ts)=>{let d2=new Date(ts*1000);return`${d2.toLocaleDateString()} ${clock(d2)}`},span=(start,end)=>{let s=Math.round(end-start);if(s<0)return"\u2014";if(s>=3600)return`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`;if(s>=60)return`${Math.floor(s/60)}m`;return`${s}s`},dur2=(s)=>s>=3600?`${Math.floor(s/3600)}h${Math.floor(s%3600/60)}m`:s>=60?`${Math.floor(s/60)}m${Math.floor(s%60)}s`:`${Math.floor(s)}s`;var import_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync3}from"fs";import{dirname as dirname8,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync4,readFileSync as readFileSync6,existsSync as existsSync12}from"fs";import{homedir as homedir5}from"os";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,$YAMLError=errors.YAMLError,$YAMLParseError=errors.YAMLParseError,$YAMLWarning=errors.YAMLWarning,$Alias=Alias.Alias,$isAlias=identity.isAlias,$isCollection=identity.isCollection,$isDocument=identity.isDocument,$isMap=identity.isMap,$isNode=identity.isNode,$isPair=identity.isPair,$isScalar=identity.isScalar,$isSeq=identity.isSeq,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,$parse=publicApi.parse,$parseAllDocuments=publicApi.parseAllDocuments,$parseDocument=publicApi.parseDocument,$stringify=publicApi.stringify,$visit=visit.visit,$visitAsync=visit.visitAsync;init_sessions_db();var HOME3=process.env.HOME||homedir5(),home={path:process.env.HERMES_HOME||`${HOME3}/.hermes`},setHome2=(h2)=>{home.path=h2},hermesPath=(relative4)=>`${home.path}/${relative4}`,managedSystem=async()=>{let env2=(process.env.HERMES_MANAGED??"").trim();if(env2){let norm=env2.toLowerCase();if(norm==="1"||norm==="true"||norm==="yes"||norm==="on")return"NixOS";return{homebrew:"Homebrew",nix:"NixOS",nixos:"NixOS"}[norm]??env2}return await Bun.file(hermesPath(".managed")).exists()?"NixOS":null},makeSource=(relative4,label)=>({file:hermesPath(relative4),relative:relative4,label:label??relative4.split("/").pop()??relative4});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
|
|
4101
|
+
`),add2=lines3.filter((l)=>/^\+(?!\+\+)/.test(l)).length,del=lines3.filter((l)=>/^-(?!--)/.test(l)).length;return{id:tool.id||`${tool.name}-${path7}`,label,diff,add:add2,del}})}var DiffTabs=import_react37.memo(({tools})=>{let theme=useTheme().theme,tabs=import_react37.useMemo(()=>buildTabs(tools),[tools]),[active,setActive]=import_react37.useState(null);if(tabs.length===0)return null;let idx=active===null?null:Math.min(active,tabs.length-1),cur=idx===null?null:tabs[idx];return $jsxs("box",{flexDirection:"column",marginTop:1,border:["left"],borderColor:theme.border,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:1,children:[$jsx("box",{flexDirection:"row",flexWrap:"wrap",backgroundColor:theme.backgroundElement,paddingX:1,children:tabs.map((t2,i)=>{let on=i===idx;return $jsx("box",{height:1,flexShrink:0,marginRight:1,paddingX:1,backgroundColor:on?theme.backgroundPanel:void 0,onMouseDown:(e)=>{e.stopPropagation(),setActive((n)=>{return(n===null?null:Math.min(n,tabs.length-1))===i?null:i})},children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?$jsx("strong",{children:t2.label}):t2.label})},t2.id)})}),cur?$jsxs($Fragment,{children:[$jsx("box",{height:1,paddingX:1,children:$jsxs("text",{children:[$jsxs("span",{fg:theme.success,children:["+",cur.add]}),$jsx("span",{fg:theme.textMuted,children:" / "}),$jsxs("span",{fg:theme.error,children:["-",cur.del]})]})}),$jsx("box",{paddingX:1,paddingBottom:1,children:$jsx(DiffBlock,{text:cur.diff})})]}):null]})});var import_react38=__toESM(require_react_production(),1);var group="approval";function question(req){return(req.description||"Shell command").trim()}function subject(req){if(req.pattern_keys?.length)return req.pattern_keys.join("|");return req.command.trim()}function mkApproval(req){return{...req,group,question:question(req),subject:subject(req)}}function shouldRemember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);return cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject)}function remember(req){let cur=get2("neverPrompts")??[],p=mkApproval(req);if(cur.some((x2)=>x2.group===p.group&&x2.question===p.question&&x2.subject===p.subject))return;set("neverPrompts",[...cur,{group:p.group,question:p.question,subject:p.subject}])}var MaskInput=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"row",height:1,position:"relative",children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:props.value,onInput:props.input,onSubmit:props.submit,focused:!0,flexGrow:1,textColor:theme.backgroundElement,cursorColor:theme.accent,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{position:"absolute",left:2,top:0,height:1,children:$jsx("text",{fg:theme.text,bg:theme.backgroundElement,children:"\u2022".repeat(props.value.length)})})]})};function digit(name){let n=parseInt(name,10);return Number.isFinite(n)?n:null}var Frame=(p)=>{let theme=useTheme().theme;return $jsx("box",{flexDirection:"column",border:["left"],borderColor:p.tint,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,marginBottom:1,children:p.children})},Pill=(p)=>{let theme=useTheme().theme;return $jsx("box",{height:1,paddingX:1,backgroundColor:p.on?theme.primary:void 0,onMouseDown:p.onPick,children:$jsxs("text",{children:[$jsxs("span",{fg:p.on?theme.background:theme.textMuted,children:[p.hot," "]}),$jsx("span",{fg:p.on?theme.background:theme.text,children:p.label})]})})},CHOICES=["once","session","never","deny"],LABELS={once:"Allow once",session:"Allow this session",never:"Never ask",deny:"Deny"},RESPOND={once:"once",session:"session",never:"always",deny:"deny"},Approval=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),[sel,setSel]=import_react38.useState(0),[steering,setSteering]=import_react38.useState(!1),[custom,setCustom]=import_react38.useState(""),[note,setNote]=import_react38.useState(""),done=import_react38.useRef(!1),prompt=mkApproval(p.req),send=(c)=>{if(done.current)return;if(done.current=!0,c==="never")remember(prompt);gw.request("approval.respond",{choice:RESPOND[c]}).catch(()=>{}),p.onAnswer(LABELS[c],c!=="deny")},steer=(text3)=>{let body=text3.trim();if(!body){setSteering(!1);return}setCustom(""),setSteering(!1),setNote("steer sent \u2014 approval still pending"),gw.request("session.steer",{text:body}).catch(()=>setNote("steer failed \u2014 approval still pending"))};return import_react38.useImperativeHandle(ref,()=>({masked:steering,feed:(key3)=>{if(steering){if(key3.name==="escape")return setSteering(!1),!0;return!1}if(key3.name==="s")return setSteering(!0),setNote(""),!0;if(key3.name==="left"||key3.name==="h")return setSel((s)=>(s+CHOICES.length-1)%CHOICES.length),!0;if(key3.name==="right"||key3.name==="l")return setSel((s)=>(s+1)%CHOICES.length),!0;if(key3.name==="return")return send(CHOICES[sel]),!0;if(key3.name==="escape")return send("deny"),!0;let n=digit(key3.name);if(n!==null&&n>=1&&n<=CHOICES.length)return send(CHOICES[n-1]),!0;return!1}}),[sel,steering]),$jsxs(Frame,{tint:theme.warning,children:[$jsxs("box",{flexDirection:"column",gap:1,paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsxs("box",{flexDirection:"row",gap:1,height:1,children:[$jsx("text",{fg:theme.warning,children:"\u25B3"}),$jsx("text",{fg:theme.text,children:"Permission required"}),$jsxs("text",{fg:theme.textMuted,children:["\xB7 ",prompt.question]})]}),$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:2,minHeight:1,children:[$jsx("text",{fg:theme.textMuted,children:"#"}),$jsx("text",{fg:theme.text,wrapMode:"word",children:p.req.description||"Shell command"})]}),$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.text,wrapMode:"word",children:["$ ",p.req.command]})}),p.req.pattern_keys?.length?$jsx("box",{paddingLeft:2,minHeight:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["matched: ",p.req.pattern_keys.join(", ")]})}):null]}),steering?$jsxs("box",{flexDirection:"column",gap:1,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>steer(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsx("text",{fg:theme.textMuted,children:"Enter steer \xB7 Esc back to approval"})]}):$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingX:2,paddingY:1,backgroundColor:theme.backgroundElement,children:[CHOICES.map((c,i)=>$jsx(Pill,{on:sel===i,hot:String(i+1),label:LABELS[c],onPick:()=>send(c)},c)),$jsx(Pill,{on:!1,hot:"s",label:"Steer",onPick:()=>{setSteering(!0),setNote("")}}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["subject: ",prompt.subject]})}),$jsx("box",{flexGrow:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2190/\u2192 \xB7 enter \xB7 s steer \xB7 esc deny"})})]}),note?$jsx("box",{paddingLeft:2,paddingBottom:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.textMuted,children:note})}):null]})}),Clarify=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,gw=useGateway(),choices=p.req.choices??[],[sel,setSel]=import_react38.useState(0),[typing,setTyping]=import_react38.useState(choices.length===0),[custom,setCustom]=import_react38.useState(""),done=import_react38.useRef(!1),send=(answer)=>{if(done.current)return;done.current=!0,gw.request("clarify.respond",{request_id:p.req.request_id,answer}).catch(()=>{}),p.onAnswer(answer||"(cancelled)",answer!=="")};import_react38.useImperativeHandle(ref,()=>({masked:typing,feed:(key3)=>{if(typing){if(key3.name==="escape"){if(choices.length)return setTyping(!1),!0;return send(""),!0}return!1}if(key3.name==="escape")return send(""),!0;if(key3.name==="up")return setSel((s)=>Math.max(0,s-1)),!0;if(key3.name==="down")return setSel((s)=>Math.min(choices.length,s+1)),!0;if(key3.name==="return"){if(sel===choices.length)return setTyping(!0),!0;let c=choices[sel];if(c)send(c);return!0}let n=digit(key3.name);if(n!==null&&n>=1&&n<=choices.length)return send(choices[n-1]),!0;return!1}}),[typing,sel,choices]);let head=$jsx("box",{minHeight:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"ask "})}),$jsx("span",{fg:theme.text,children:$jsx("strong",{children:p.req.question})})]})});return $jsx(Frame,{tint:theme.accent,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[head,$jsx("box",{height:1}),typing?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{fg:theme.textMuted,children:"> "}),$jsx("input",{value:custom,onInput:setCustom,onSubmit:()=>send(custom),focused:!0,flexGrow:1,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})]}),$jsxs("text",{fg:theme.textMuted,children:["Enter send \xB7 Esc ",choices.length?"back":"cancel"]})]}):$jsxs($Fragment,{children:[[...choices,"Other (type your answer)"].map((c,i)=>$jsx("box",{height:1,onMouseDown:()=>i===choices.length?setTyping(!0):send(choices[i]),children:$jsxs("text",{fg:sel===i?theme.text:theme.textMuted,children:[sel===i?"\u25B8 ":" ",i+1,". ",c]})},i)),$jsx("box",{height:1}),$jsxs("text",{fg:theme.textMuted,children:["\u2191/\u2193 \xB7 Enter \xB7 1-",choices.length," \xB7 Esc cancel"]})]})]})})}),Masked=import_react38.forwardRef((p,ref)=>{let theme=useTheme().theme,[value,setValue]=import_react38.useState(""),done=import_react38.useRef(!1),go=(v2)=>{if(done.current)return;done.current=!0,p.onSubmit(v2),p.onAnswer(v2?"(provided)":"(cancelled)",v2!=="")};return import_react38.useImperativeHandle(ref,()=>({masked:!0,feed:(key3)=>{if(key3.name==="escape")return go(""),!0;return!1}}),[]),$jsx(Frame,{tint:theme.warning,children:$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:2,paddingY:1,children:[$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})}),$jsx("text",{fg:theme.text,children:p.note}),$jsx("box",{height:1}),$jsx(MaskInput,{value,input:setValue,submit:()=>go(value)}),$jsx("text",{fg:theme.textMuted,children:"Enter submit \xB7 Esc cancel"})]})})}),Outcome=import_react38.memo(({part})=>{let theme=useTheme().theme,a=part.answered,glyph=a.ok?"\u2713":"\u2717",fg2=a.ok?theme.success:theme.error,what=part.variant==="approval"?a.label:part.variant==="clarify"?`chose: ${a.label}`:part.variant==="sudo"?`sudo ${a.label}`:`${part.req.env_var??"secret"} ${a.label}`;return $jsx("box",{height:1,paddingLeft:3,marginBottom:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[glyph," "]}),$jsx("span",{fg:theme.textMuted,children:what})]})})}),PromptCard=import_react38.memo(import_react38.forwardRef((p,ref)=>{let gw=useGateway();if(p.part.answered)return $jsx(Outcome,{part:p.part});let answer=(label,ok)=>p.onAnswer(p.part.id,label,ok),req=p.part.req;if(req.variant==="approval")return $jsx(Approval,{ref,req,onAnswer:answer});if(req.variant==="clarify")return $jsx(Clarify,{ref,req,onAnswer:answer});if(req.variant==="sudo")return $jsx(Masked,{ref,title:"\uD83D\uDD12 Sudo required",note:"Enter your password to elevate privileges.",onSubmit:(v2)=>void gw.request("sudo.respond",{request_id:req.request_id,password:v2}).catch(()=>{}),onAnswer:answer});return $jsx(Masked,{ref,title:`\uD83D\uDD11 Secret: ${req.env_var}`,note:req.prompt,onSubmit:(v2)=>void gw.request("secret.respond",{request_id:req.request_id,value:v2}).catch(()=>{}),onAnswer:answer})}));function pending2(messages){for(let i=messages.length-1;i>=0;i--){let m2=messages[i];if(m2.role!=="assistant")continue;for(let j2=m2.parts.length-1;j2>=0;j2--){let part=m2.parts[j2];if(part.type==="prompt"&&!part.answered)return part}}return null}var import_react39=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import{existsSync as existsSync10,statSync as statSync2}from"fs";function parseChafaLine(line){let out=[],fg2=null,bg2=null,reverse2=!1,i=0,N2=line.length;while(i<N2){if(line.charCodeAt(i)===27&&line.charCodeAt(i+1)===91){let end=line.indexOf("m",i+2);if(end<0){i=N2;break}let params=line.slice(i+2,end).split(";").map((x2)=>parseInt(x2,10)||0),p=0;while(p<params.length){let n=params[p];if(n===0){fg2=null,bg2=null,reverse2=!1,p++;continue}if(n===7){reverse2=!0,p++;continue}if(n===27){reverse2=!1,p++;continue}if(n===38&¶ms[p+1]===2){fg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===48&¶ms[p+1]===2){bg2={r:params[p+2]|0,g:params[p+3]|0,b:params[p+4]|0},p+=5;continue}if(n===39){fg2=null,p++;continue}if(n===49){bg2=null,p++;continue}p++}i=end+1;continue}let cp=line.codePointAt(i),ch=String.fromCodePoint(cp);i+=ch.length;let efg=reverse2?bg2:fg2,ebg=reverse2?fg2:bg2;out.push({ch,fg:efg,bg:ebg})}return out}function parseChafa(text3){return text3.split(`
|
|
4102
|
+
`).filter((s)=>s.length>0).map(parseChafaLine)}function hex(c){if(!c)return;return`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`}var CHAFA_PATHS=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa","/home/linuxbrew/.linuxbrew/bin/chafa"],cachedBin=void 0;function chafaBin(){if(cachedBin!==void 0)return cachedBin;for(let p of CHAFA_PATHS)if(existsSync10(p))return cachedBin=p,p;return cachedBin=null,null}function resolveImage(path7){let full=path7.startsWith("~")?(process.env.HOME??"")+path7.slice(1):path7;return existsSync10(full)?full:null}var CACHE=new Map,CACHE_CAP=50;function cacheGet(k2){let v2=CACHE.get(k2);if(!v2)return;return CACHE.delete(k2),CACHE.set(k2,v2),v2}function cachePut(k2,v2){if(CACHE.size>=CACHE_CAP)CACHE.delete(CACHE.keys().next().value);CACHE.set(k2,v2)}function renderChafa(path7,width,height){let bin=chafaBin();if(!bin)return{err:"chafa not installed"};let full=resolveImage(path7);if(!full)return{err:`not found: ${path7}`};let mtime=0;try{mtime=statSync2(full).mtimeMs|0}catch{}let h2=height??Math.max(6,Math.round(width/3)),key3=`${full}:${mtime}:${width}x${h2}`,cached2=cacheGet(key3);if(cached2)return{rows:cached2};let r=spawnSync(bin,[`--size=${width}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8",timeout:5000});if(r.error)return{err:r.error.message};if(r.status!==0)return{err:(r.stderr||`chafa exit ${r.status}`).trim()};let rows2=parseChafa(r.stdout);return cachePut(key3,rows2),{rows:rows2}}var basename8=(p)=>p.split(/[/\\]/).pop()||p,ChafaImage=import_react39.memo(({path:path7,width})=>{let theme=useTheme().theme,[collapsed,setCollapsed]=import_react39.useState(!1),w2=Math.max(20,Math.min(80,width??60)),hasChafa=chafaBin()!==null,result=import_react39.useMemo(()=>hasChafa?renderChafa(path7,w2):{err:"chafa not installed"},[path7,w2,hasChafa]);if(!hasChafa||"err"in result)return $jsx(MediaChip,{path:path7});if(collapsed)return $jsx(MediaChip,{path:path7,onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!1)}});return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation(),setCollapsed(!0)},children:result.rows.map((row3,i)=>$jsx("text",{children:row3.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,onMouseDown:(e)=>{e.stopPropagation(),openFile(path7)},children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.accent,children:"\u25C9 "}),$jsx("span",{fg:theme.text,children:basename8(path7)}),$jsx("span",{fg:theme.textMuted,children:" click image to collapse \xB7 click name to open"})]})})]})});var import_react40=__toESM(require_react_production(),1);var SKINS=["default","ares","mono","slate","daylight","warm-lightmode","poseidon","sisyphus","charizard"],DEFAULT={agentName:"Hermes"},Ctx4=import_react40.createContext(DEFAULT);function deriveSkin(skin){let name=skin?.branding?.agent_name?.trim();return{skin:skin??void 0,agentName:name||"Hermes"}}var SkinProvider=import_react40.memo(({value,children})=>$jsx(Ctx4.Provider,{value,children}));function useSkin(){return import_react40.useContext(Ctx4)}var SYMBOLS={"\\alpha":"\u03B1","\\beta":"\u03B2","\\gamma":"\u03B3","\\delta":"\u03B4","\\epsilon":"\u03B5","\\varepsilon":"\u03B5","\\zeta":"\u03B6","\\eta":"\u03B7","\\theta":"\u03B8","\\vartheta":"\u03D1","\\iota":"\u03B9","\\kappa":"\u03BA","\\lambda":"\u03BB","\\mu":"\u03BC","\\nu":"\u03BD","\\xi":"\u03BE","\\pi":"\u03C0","\\varpi":"\u03D6","\\rho":"\u03C1","\\varrho":"\u03F1","\\sigma":"\u03C3","\\varsigma":"\u03C2","\\tau":"\u03C4","\\upsilon":"\u03C5","\\phi":"\u03C6","\\varphi":"\u03C6","\\chi":"\u03C7","\\psi":"\u03C8","\\omega":"\u03C9","\\Gamma":"\u0393","\\Delta":"\u0394","\\Theta":"\u0398","\\Lambda":"\u039B","\\Xi":"\u039E","\\Pi":"\u03A0","\\Sigma":"\u03A3","\\Upsilon":"\u03A5","\\Phi":"\u03A6","\\Psi":"\u03A8","\\Omega":"\u03A9","\\sum":"\u2211","\\prod":"\u220F","\\coprod":"\u2210","\\int":"\u222B","\\iint":"\u222C","\\iiint":"\u222D","\\oint":"\u222E","\\bigcup":"\u22C3","\\bigcap":"\u22C2","\\bigvee":"\u22C1","\\bigwedge":"\u22C0","\\bigoplus":"\u2A01","\\bigotimes":"\u2A02","\\partial":"\u2202","\\nabla":"\u2207","\\sqrt":"\u221A","\\emptyset":"\u2205","\\varnothing":"\u2205","\\infty":"\u221E","\\in":"\u2208","\\notin":"\u2209","\\ni":"\u220B","\\subset":"\u2282","\\supset":"\u2283","\\subseteq":"\u2286","\\supseteq":"\u2287","\\subsetneq":"\u228A","\\supsetneq":"\u228B","\\cup":"\u222A","\\cap":"\u2229","\\setminus":"\u2216","\\complement":"\u2201","\\forall":"\u2200","\\exists":"\u2203","\\nexists":"\u2204","\\land":"\u2227","\\lor":"\u2228","\\lnot":"\xAC","\\neg":"\xAC","\\therefore":"\u2234","\\because":"\u2235","\\le":"\u2264","\\leq":"\u2264","\\ge":"\u2265","\\geq":"\u2265","\\ne":"\u2260","\\neq":"\u2260","\\ll":"\u226A","\\gg":"\u226B","\\approx":"\u2248","\\equiv":"\u2261","\\cong":"\u2245","\\sim":"\u223C","\\simeq":"\u2243","\\propto":"\u221D","\\perp":"\u22A5","\\parallel":"\u2225","\\models":"\u22A8","\\vdash":"\u22A2","\\mid":"\u2223","\\nmid":"\u2224","\\divides":"\u2223","\\blacksquare":"\u25A0","\\square":"\u25A1","\\Box":"\u25A1","\\qed":"\u220E","\\bigstar":"\u2605","\\bmod":"mod","\\mod":"mod","\\langle":"\u27E8","\\rangle":"\u27E9","\\lceil":"\u2308","\\rceil":"\u2309","\\lfloor":"\u230A","\\rfloor":"\u230B","\\|":"\u2016","\\to":"\u2192","\\rightarrow":"\u2192","\\leftarrow":"\u2190","\\leftrightarrow":"\u2194","\\Rightarrow":"\u21D2","\\Leftarrow":"\u21D0","\\Leftrightarrow":"\u21D4","\\implies":"\u27F9","\\impliedby":"\u27F8","\\iff":"\u27FA","\\mapsto":"\u21A6","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\uparrow":"\u2191","\\downarrow":"\u2193","\\updownarrow":"\u2195","\\cdot":"\u22C5","\\cdots":"\u22EF","\\ldots":"\u2026","\\dots":"\u2026","\\dotsb":"\u2026","\\dotsc":"\u2026","\\vdots":"\u22EE","\\ddots":"\u22F1","\\times":"\xD7","\\div":"\xF7","\\pm":"\xB1","\\mp":"\u2213","\\circ":"\u2218","\\bullet":"\u2022","\\star":"\u22C6","\\ast":"\u2217","\\oplus":"\u2295","\\ominus":"\u2296","\\otimes":"\u2297","\\odot":"\u2299","\\diamond":"\u22C4","\\angle":"\u2220","\\triangle":"\u25B3","\\,":" ","\\;":" ","\\:":" ","\\!":"","\\ ":" ","\\quad":" ","\\qquad":" ","\\sin":"sin","\\cos":"cos","\\tan":"tan","\\cot":"cot","\\sec":"sec","\\csc":"csc","\\arcsin":"arcsin","\\arccos":"arccos","\\arctan":"arctan","\\sinh":"sinh","\\cosh":"cosh","\\tanh":"tanh","\\log":"log","\\ln":"ln","\\exp":"exp","\\det":"det","\\dim":"dim","\\ker":"ker","\\lim":"lim","\\liminf":"liminf","\\limsup":"limsup","\\sup":"sup","\\inf":"inf","\\max":"max","\\min":"min","\\arg":"arg","\\gcd":"gcd","\\&":"&","\\%":"%","\\$":"$","\\#":"#","\\_":"_","\\{":"{","\\}":"}"},BB={A:"\uD835\uDD38",B:"\uD835\uDD39",C:"\u2102",D:"\uD835\uDD3B",E:"\uD835\uDD3C",F:"\uD835\uDD3D",G:"\uD835\uDD3E",H:"\u210D",I:"\uD835\uDD40",J:"\uD835\uDD41",K:"\uD835\uDD42",L:"\uD835\uDD43",M:"\uD835\uDD44",N:"\u2115",O:"\uD835\uDD46",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\uD835\uDD4A",T:"\uD835\uDD4B",U:"\uD835\uDD4C",V:"\uD835\uDD4D",W:"\uD835\uDD4E",X:"\uD835\uDD4F",Y:"\uD835\uDD50",Z:"\u2124"},CAL={A:"\uD835\uDC9C",B:"\u212C",C:"\uD835\uDC9E",D:"\uD835\uDC9F",E:"\u2130",F:"\u2131",G:"\uD835\uDCA2",H:"\u210B",I:"\u2110",J:"\uD835\uDCA5",K:"\uD835\uDCA6",L:"\u2112",M:"\u2133",N:"\uD835\uDCA9",O:"\uD835\uDCAA",P:"\uD835\uDCAB",Q:"\uD835\uDCAC",R:"\u211B",S:"\uD835\uDCAE",T:"\uD835\uDCAF",U:"\uD835\uDCB0",V:"\uD835\uDCB1",W:"\uD835\uDCB2",X:"\uD835\uDCB3",Y:"\uD835\uDCB4",Z:"\uD835\uDCB5"},FRAK={A:"\uD835\uDD04",B:"\uD835\uDD05",C:"\u212D",D:"\uD835\uDD07",E:"\uD835\uDD08",F:"\uD835\uDD09",G:"\uD835\uDD0A",H:"\u210C",I:"\u2111",J:"\uD835\uDD0D",K:"\uD835\uDD0E",L:"\uD835\uDD0F",M:"\uD835\uDD10",N:"\uD835\uDD11",O:"\uD835\uDD12",P:"\uD835\uDD13",Q:"\uD835\uDD14",R:"\u211C",S:"\uD835\uDD16",T:"\uD835\uDD17",U:"\uD835\uDD18",V:"\uD835\uDD19",W:"\uD835\uDD1A",X:"\uD835\uDD1B",Y:"\uD835\uDD1C",Z:"\u2128"},SUPERSCRIPT={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPT={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var escapeRe=(s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),splitByEnding=(keys)=>{let letter=[],punct=[];for(let k2 of keys)if(/[A-Za-z]$/.test(k2))letter.push(k2);else punct.push(k2);return{letter,punct}},buildAlt=(cmds)=>cmds.sort((a,b2)=>b2.length-a.length).map(escapeRe).join("|"),{letter:LETTER_CMDS,punct:PUNCT_CMDS}=splitByEnding(Object.keys(SYMBOLS)),SYMBOL_LETTER_RE=new RegExp("(?:"+buildAlt(LETTER_CMDS)+")(?![A-Za-z])","g"),SYMBOL_PUNCT_RE=new RegExp("(?:"+buildAlt(PUNCT_CMDS)+")","g"),convertScript=(input,table,sigil)=>{let out="",allMapped=!0;for(let ch of input){let mapped=table[ch];if(!mapped){allMapped=!1;break}out+=mapped}if(allMapped)return out;let trimmed=input.trim();if([...trimmed].length===1)return`${sigil}${trimmed}`;return`${sigil}(${trimmed})`},readBraced=(s,start)=>{if(s[start]!=="{")return null;let depth=1,i=start+1;while(i<s.length&&depth>0){let c=s[i];if(c==="\\"&&i+1<s.length){i+=2;continue}if(c==="{")depth++;else if(c==="}")depth--;if(depth>0)i++}if(depth!==0)return null;return{content:s.slice(start+1,i),end:i+1}},replaceBracedCommand=(input,command,render)=>{let cmdLen=command.length,out="",i=0;while(i<input.length){let idx=input.indexOf(command,i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+cmdLen];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+cmdLen),i=idx+cmdLen;continue}out+=input.slice(i,idx);let p=idx+cmdLen;while(input[p]===" "||input[p]==="\t")p++;let arg=readBraced(input,p);if(!arg){out+=input.slice(idx,p+1),i=p+1;continue}out+=render(replaceBracedCommand(arg.content,command,render)),i=arg.end}return out},replaceFracs=(input)=>{let out="",i=0;while(i<input.length){let idx=input.indexOf("\\frac",i);if(idx<0)return out+=input.slice(i),out;let after=input[idx+5];if(after&&/[A-Za-z]/.test(after)){out+=input.slice(i,idx+5),i=idx+5;continue}out+=input.slice(i,idx);let p=idx+5;while(input[p]===" "||input[p]==="\t")p++;let num2=readBraced(input,p);if(!num2){out+=input.slice(idx,p+1),i=p+1;continue}p=num2.end;while(input[p]===" "||input[p]==="\t")p++;let den=readBraced(input,p);if(!den){out+=input.slice(idx,p+1),i=p+1;continue}out+=`${wrapForFrac(replaceFracs(num2.content))}/${wrapForFrac(replaceFracs(den.content))}`,i=den.end}return out},wrapForFrac=(expr)=>{let trimmed=expr.trim();if(!trimmed)return trimmed;if(/^\(.*\)$/.test(trimmed))return trimmed;if(/[+\-/*]|\s/.test(trimmed))return`(${trimmed})`;return trimmed};function texToUnicode(input){let s=input;return s=s.replace(/\\mathbb\s*\{([A-Za-z])\}/g,(raw,c)=>BB[c]??raw),s=s.replace(/\\mathcal\s*\{([A-Za-z])\}/g,(raw,c)=>CAL[c]??raw),s=s.replace(/\\mathfrak\s*\{([A-Za-z])\}/g,(raw,c)=>FRAK[c]??raw),s=s.replace(/\\mathbf\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathit\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\mathrm\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\text\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\operatorname\s*\{([^{}]+)\}/g,(_2,c)=>c),s=s.replace(/\\overline\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0305`),s=s.replace(/\\hat\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0302`),s=s.replace(/\\bar\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0304`),s=s.replace(/\\tilde\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0303`),s=s.replace(/\\vec\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u20D7`),s=s.replace(/\\dot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0307`),s=s.replace(/\\ddot\s*\{([^{}]+)\}/g,(_2,c)=>`${c}\u0308`),s=replaceFracs(s),s=replaceBracedCommand(s,"\\boxed",(body)=>`**${body.trim()}**`),s=replaceBracedCommand(s,"\\fbox",(body)=>`**${body.trim()}**`),s=s.replace(/\\xrightarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2500${label.trim()}\u2192`),s=s.replace(/\\xleftarrow\s*\{([^{}]*)\}/g,(_2,label)=>`\u2190${label.trim()}\u2500`),s=s.replace(/\\Longrightarrow/g,"\u27F9"),s=s.replace(/\\Longleftarrow/g,"\u27F8"),s=s.replace(/\\Longleftrightarrow/g,"\u27FA"),s=s.replace(/\s*\\pmod\s*\{([^{}]*)\}/g,(_2,p)=>` (mod ${p.trim()})`),s=s.replace(/\s*\\pod\s*\{([^{}]*)\}/g,(_2,p)=>` (${p.trim()})`),s=s.replace(/\s*\\tag\s*\{([^{}]*)\}/g,(_2,n)=>` (${n.trim()})`),s=s.replace(/\\(?:Bigg|bigg|Big|big)[lrm]?(?![A-Za-z])/g,""),s=s.replace(/\\(?:scriptscriptstyle|displaystyle|scriptstyle|textstyle|nolimits|limits)(?![A-Za-z])\s*/g,""),s=s.replace(/\\left(?![A-Za-z])\.?/g,""),s=s.replace(/\\right(?![A-Za-z])\.?/g,""),s=s.replace(SYMBOL_PUNCT_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(SYMBOL_LETTER_RE,(m2)=>SYMBOLS[m2]??m2),s=s.replace(/\^\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUPERSCRIPT,"^")),s=s.replace(/\^([A-Za-z0-9+\-=])/g,(raw,ch)=>SUPERSCRIPT[ch]??raw),s=s.replace(/_\s*\{([^{}]+)\}/g,(_2,body)=>convertScript(body,SUBSCRIPT,"_")),s=s.replace(/_([A-Za-z0-9+\-=])/g,(raw,ch)=>SUBSCRIPT[ch]??raw),s}var CODE_SPAN_RE=/(`{1,2})[^`\n]+?\1/g,MATH_SPAN_RE=new RegExp([String.raw`\$\$([^$]+?)\$\$`,String.raw`\\\[([\s\S]+?)\\\]`,String.raw`\\\(([^\n]+?)\\\)`,String.raw`(?<!\$)\$([^\s$](?:[^$\n]*?[^\s$])?)\$(?!\$)`].join("|"),"g");function mathify(md){if(!/[$\\]/.test(md))return md;let out="",i=0;CODE_SPAN_RE.lastIndex=0;for(let m2 of md.matchAll(CODE_SPAN_RE))out+=md.slice(i,m2.index).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out+=m2[0],i=m2.index+m2[0].length;return out+=md.slice(i).replace(MATH_SPAN_RE,(_2,a,b2,c,d2)=>texToUnicode(a??b2??c??d2)),out}function duration(ms2){if(ms2<1000)return`${ms2}ms`;let s=ms2/1000;if(s<60)return`${s.toFixed(1)}s`;return`${Math.floor(s/60)}m${Math.floor(s%60)}s`}function tokens2(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}function extract(msg){return msg.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("")}var trunc3=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026";function mix(a,b2,n=0.5){return RGBA.fromValues(a.r+(b2.r-a.r)*n,a.g+(b2.g-a.g)*n,a.b+(b2.b-a.b)*n,a.a+(b2.a-a.a)*n)}var TOP_RULE={topLeft:"\u2594",topRight:"\u2594",horizontal:"\u2594",bottomLeft:"",bottomRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""},BOTTOM_RULE={bottomLeft:"\u2581",bottomRight:"\u2581",horizontal:"\u2581",topLeft:"",topRight:"",vertical:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""};function useClick(fn){let at=import_react41.useRef(null);return{onMouseDown:(e)=>{at.current={x:e.x,y:e.y}},onMouseUp:(e)=>{let a=at.current;if(at.current=null,fn&&a&&a.x===e.x&&a.y===e.y)fn()}}}var Gutter2=import_react41.memo(({color,glyph="\u2502",side="left",children})=>{let bar=$jsx("box",{width:2,flexShrink:0,border:[side],borderColor:color,customBorderChars:{topLeft:glyph,bottomLeft:glyph,vertical:glyph,topRight:glyph,bottomRight:glyph,horizontal:"",topT:"",bottomT:"",leftT:"",rightT:"",cross:""}});return $jsxs("box",{flexDirection:"row",children:[side==="left"?bar:null,$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children}),side==="right"?bar:null]})}),MessageItem=import_react41.memo(({message,streaming,prompt,onRewind,onPick})=>{if(message.role==="system")return $jsx(SystemMessage,{message});if(message.role==="user")return $jsx(UserMessage,{message,onRewind});return $jsx(AssistantMessage,{message,streaming,prompt,onPick})}),SystemMessage=import_react41.memo(({message})=>{let theme=useTheme().theme;return $jsx("box",{marginBottom:1,children:$jsx(Gutter2,{color:theme.textMuted,glyph:"\xB7",children:$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:extract(message)})})})})}),UserMessage=import_react41.memo(({message,onRewind})=>{let theme=useTheme().theme,[hover,setHover]=import_react41.useState(!1),click=useClick(onRewind&&(()=>onRewind(message))),rule=import_react41.useMemo(()=>mix(theme.background,theme.backgroundElement),[theme.background,theme.backgroundElement]),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]);return $jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,border:["bottom"],customBorderChars:BOTTOM_RULE,borderColor:rule}),$jsx("box",{backgroundColor:hover?rule:theme.backgroundElement,paddingLeft:1,paddingRight:1,paddingY:1,flexDirection:"column",minHeight:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:message.parts.map((p,i)=>{let seg=segs[i];if(!seg)return null;let k2=p.key??i;return seg.map((s,j2)=>{if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang},`${k2}-c${j2}`);return $jsx("text",{fg:theme.text,wrapMode:"word",children:s.md},`${k2}-${j2}`)})})}),$jsx("box",{height:1,border:["top"],customBorderChars:TOP_RULE,borderColor:rule})]})}),AssistantMessage=import_react41.memo(({message,streaming,prompt,onPick})=>{let ctx=useTheme(),theme=ctx.theme,{agentName}=useSkin(),[hover,setHover]=import_react41.useState(!1),click=useClick(onPick&&(()=>onPick(message))),err=!!message.error,trail=message.parts.filter((p)=>p.type==="tool"||p.type==="prompt"),diffs=trail.filter((p)=>p.type==="tool"&&(!!p.diff||isDiff(p.result))),segs=import_react41.useMemo(()=>message.parts.map((p)=>p.type==="text"&&p.content?splitContent(p.content):null),[message.parts]),header=[agentName,message.usage?`${tokens2(message.usage.input)}\u2192${tokens2(message.usage.output)} tok`:null,message.duration?duration(message.duration):null].filter(Boolean).join(" \xB7 "),part=(p,i)=>{if(p.type==="prompt")return $jsx("box",{marginTop:1,onMouseDown:(e)=>e.stopPropagation(),children:$jsx(PromptCard,{part:p,ref:!p.answered?prompt?.ref:void 0,onAnswer:prompt?.onAnswer??(()=>{})})},`pr-${p.id}`);let seg=segs[i];if(!seg)return null;let k2=p.key??i,last=streaming&&p.streaming;return seg.map((s,j2)=>{let tail=last&&j2===seg.length-1;if("media"in s)return classify(s.media)==="img"?$jsx("box",{children:$jsx(ChafaImage,{path:s.media})},`${k2}-m${j2}`):$jsx("box",{marginTop:1,children:$jsx(MediaChip,{path:s.media})},`${k2}-m${j2}`);if("code"in s)return $jsx(CodeBlock,{code:s.code,lang:s.lang,streaming:tail},`${k2}-c${j2}`);return $jsx("box",{children:$jsx("markdown",{content:mathify(s.md),fg:theme.markdownText,syntaxStyle:ctx.syntaxStyle,streaming:tail})},`${k2}-${j2}`)})};return $jsxs("box",{flexDirection:"row",marginBottom:1,onMouseOver:()=>setHover(!0),onMouseOut:()=>setHover(!1),...click,children:[$jsx("box",{width:3,flexShrink:0,backgroundColor:hover?theme.backgroundElement:void 0}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.textMuted,children:header})}),trail.length?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:trunc3(trail.map((p)=>p.type==="tool"?p.name:"?").join(" \xB7 "),40)})}):null]}),message.parts.map(part),diffs.length?$jsx(DiffTabs,{tools:diffs}):null,err?$jsx(ErrorBlock,{text:message.error}):null]})]})});var import_react42=__toESM(require_react_production(),1);var VERBS=["Thinking\u2026","Considering\u2026","Working\u2026","Pondering\u2026"],TypingIndicator=import_react42.memo((props)=>{let theme=useTheme().theme,[i,setI]=import_react42.useState(0);return import_react42.useEffect(()=>{if(props.label)return;let id=setInterval(()=>setI((n)=>(n+1)%VERBS.length),2200);return()=>clearInterval(id)},[props.label]),$jsx("box",{height:1,paddingLeft:1,children:$jsx(Spinner,{color:theme.info,label:props.label??VERBS[i]})})});var MessageList=import_react43.memo(({messages,streaming,prompt,onRewind,onPick})=>{let theme=useTheme().theme,style=import_react43.useMemo(()=>({viewportOptions:{backgroundColor:theme.background},scrollbarOptions:{trackOptions:{foregroundColor:theme.borderSubtle,backgroundColor:theme.background}}}),[theme]);if(messages.length===0)return $jsx("box",{flexGrow:1});let last=messages[messages.length-1],lastStreaming=streaming&&last?.role==="assistant",firstUser=messages.findIndex((m2)=>m2.role==="user");return $jsx("scrollbox",{flexGrow:1,scrollY:!0,stickyScroll:!0,stickyStart:"bottom",style,children:$jsxs("box",{flexDirection:"column",paddingBottom:1,children:[messages.map((msg,i)=>$jsxs("box",{flexDirection:"column",children:[msg.role==="user"&&i>firstUser?$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"\u2500\u2500\u2500"})}):null,$jsx(MessageItem,{message:msg,streaming:lastStreaming&&i===messages.length-1,prompt,onRewind,onPick})]},msg.id)),streaming&&last?.role!=="assistant"&&$jsx(TypingIndicator,{})]})})});var Chat=import_react44.memo(({messages,streaming,prompt,cloud,cloudH,pick,onResize,onPick,onClose,onRewind})=>{let theme=useTheme().theme;return $jsxs("box",{flexGrow:1,flexDirection:"column",position:"relative",backgroundColor:theme.background,children:[$jsx(MessageList,{messages,streaming,prompt,onRewind,onPick}),cloud?$jsx("box",{position:"absolute",top:0,left:0,right:0,zIndex:1,children:$jsx(ThoughtCloud,{height:cloudH,messages,pick,onResize,onClose})}):null]})});var import_react62=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);init_sessions_db();import{existsSync as existsSync11}from"fs";import{homedir as homedir4}from"os";import{join as join10}from"path";var INLINE=process.env.HERM_IO_INLINE==="1",HOME2=()=>process.env.HERMES_HOME||join10(homedir4(),".hermes"),entry=()=>{let js=join10(import.meta.dirname,"db.worker.js");return new URL(existsSync11(js)?"./db.worker.js":"./db.worker.ts",import.meta.url)},state={w:null,seq:0,pending:new Map,inline:null},spawn2=()=>{if(state.w)return state.w;let w2=new Worker(entry());return w2.onmessage=(e)=>{let r=e.data;state.pending.get(r.id)?.(r),state.pending.delete(r.id)},w2.onerror=(ev)=>{let err=`io worker: ${ev.message}`;for(let res of state.pending.values())res({id:-1,ok:!1,err});state.pending.clear()},state.w=w2},call=(fn,args)=>{if(INLINE)return state.inline??=Promise.resolve().then(() => (init_fns(),exports_fns)).then((m2)=>m2.FNS),state.inline.then((f)=>f[fn](...args));return new Promise((resolve4,reject)=>{let id=++state.seq;state.pending.set(id,(r)=>r.ok?resolve4(r.v):reject(Error(r.err))),spawn2().postMessage({id,home:HOME2(),fn,args})})},io=new Proxy({},{get:(_2,fn)=>(...args)=>call(fn,args)}),warm=()=>{if(!INLINE)call("roots",[0])};var import_react45=__toESM(require_react_production(),1);var Ctx5=import_react45.createContext(null),BACKDROP=RGBA.fromInts(0,0,0,150),DialogProvider=({children:children2})=>{let renderer=useRenderer(),toast=useToast(),[stack,setStack]=import_react45.useState([]),gate=import_react45.useRef(!1),gen=import_react45.useRef(0),prev=import_react45.useRef(null),refocus=import_react45.useCallback(()=>{setTimeout(()=>{if(gate.current)return;let target=prev.current;if(!target||target.isDestroyed){prev.current=null;return}let reachable=(node)=>{for(let c of node.getChildren())if(c===target||reachable(c))return!0;return!1};if(reachable(renderer.root))target.focus();prev.current=null},0)},[renderer]),replace=import_react45.useCallback((element,onClose,opts)=>{if(!gate.current&&!prev.current)prev.current=renderer.currentFocusedRenderable,prev.current?.blur();gate.current=!0,gen.current++,setStack((cur)=>{for(let e of cur)e.onClose?.();return[{element,onClose,ownCancel:opts?.ownCancel}]})},[renderer]),clear=import_react45.useCallback(()=>{setStack((cur)=>{for(let e of cur)e.onClose?.();return[]});let at=gen.current;queueMicrotask(()=>{if(gen.current===at)gate.current=!1}),refocus()},[refocus]),open2=import_react45.useCallback(()=>gate.current,[]),onError=import_react45.useCallback((err)=>{clear(),toast.error(err)},[clear,toast]),keys=useKeys();useKeyboard((key3)=>{if(stack.length===0)return;if(renderer.getSelection()?.getSelectedText())return;if(stack[stack.length-1]?.ownCancel)return;if(keys.match("dialog.cancel",key3))clear()});let value=import_react45.useMemo(()=>({replace,clear,stack,open:open2}),[replace,clear,stack,open2]),top=stack[stack.length-1];return $jsxs(Ctx5.Provider,{value,children:[children2,top?$jsx(Boundary,{onError,children:$jsx(Overlay,{entry:top,onClose:clear})}):null]})};class Boundary extends import_react45.Component{state={dead:!1};static getDerivedStateFromError(){return{dead:!0}}componentDidCatch(err,_info){this.props.onError(err)}render(){if(this.state.dead)return null;return this.props.children}}var Overlay=({entry:entry2,onClose})=>{let dims=useTerminalDimensions(),theme=useTheme().theme,renderer=useRenderer(),armed=import_react45.useRef(!1);return $jsx("box",{position:"absolute",left:0,top:0,width:dims.width,height:dims.height,zIndex:100,backgroundColor:BACKDROP,justifyContent:"center",alignItems:"center",onMouseDown:()=>{armed.current=!renderer.getSelection()},onMouseUp:()=>{if(!armed.current)return;armed.current=!1,onClose()},children:$jsx("box",{backgroundColor:theme.backgroundPanel,borderStyle:"single",border:!0,borderColor:theme.border,padding:1,flexDirection:"column",onMouseDown:(e)=>{e.stopPropagation()},onMouseUp:(e)=>{armed.current=!1,e.stopPropagation()},children:entry2.element})})},useDialog=makeUse(Ctx5,"useDialog");var TabShell=(props)=>{let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",flexGrow:props.grow??1,flexBasis:0,minWidth:0,minHeight:0,border:!0,borderColor:props.focus?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,padding:1,children:[$jsxs("box",{height:1,overflow:"hidden",flexDirection:"row",children:[$jsx("box",{flexShrink:0,overflow:"hidden",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:$jsx("strong",{children:props.title})})}),props.titleRight?$jsx("box",{flexGrow:1,minWidth:0,overflow:"hidden",justifyContent:"flex-end",children:props.titleRight}):null]}),props.error?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:`\u26A0 ${props.error}`})}):null,$jsx("box",{height:1}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,overflow:"hidden",children:props.children})]})};var import_react47=__toESM(require_react_production(),1);var HintBar=import_react47.memo((props)=>{let theme=useTheme().theme,text3=props.pairs?props.pairs.map((p)=>`[${p[0]}] ${p[1]}`).join(" ")+(props.suffix?` \xB7 ${props.suffix}`:""):props.raw??"";return $jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:text3})})});var KV=(props)=>{let theme=useTheme().theme;return $jsxs("box",{minHeight:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:props.wrap?void 0:1,overflow:props.wrap?void 0:"hidden",children:$jsx("text",{wrapMode:props.wrap?"word":void 0,fg:props.fg??theme.text,children:props.value})})]})},KVBlock=(props)=>props.rows.map(([k2,v2,fg2])=>v2===void 0?null:$jsx(KV,{label:k2,value:v2,fg:fg2},k2));var import_react48=__toESM(require_react_production(),1);var VBAR_W=1,VBAR={visible:!0},Col=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text;return $jsx("box",{width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",onMouseDown:p.onClick,flexDirection:"row",justifyContent:p.right?"flex-end":"flex-start",children:$jsx("text",{children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:p.children})}):$jsx("span",{fg:fg2,children:p.children})})})},Hdr=(p)=>$jsx("box",{flexDirection:"row",height:1,paddingRight:VBAR_W,children:p.children}),Marquee=(p)=>{let theme=useTheme().theme,fg2=p.fg??theme.text,text3=p.children,box=import_react48.useRef(null),node=import_react48.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,[wraps,setWraps]=import_react48.useState(!1);import_react48.useEffect(()=>{let tn=node.current;if(!tn)return;let w2=box.current?.width??0;if(setWraps(text3.length>w2),!animate){tn.scrollX=0;return}let id,period=text3.length+GAP.length,hold=setTimeout(()=>{id=setInterval(()=>{let cur=box.current?.width??0;if(text3.length<=cur){tn.scrollX=0;return}tn.scrollX=(tn.scrollX+1)%period},p.speed??180)},p.hold??600);return()=>{if(clearTimeout(hold),id)clearInterval(id);if(node.current)node.current.scrollX=0}},[animate,text3,p.speed,p.hold]);let body=wraps?text3+GAP+text3:text3;return $jsx("box",{ref:box,width:p.w,flexGrow:p.grow?1:0,flexShrink:p.grow?1:0,minWidth:p.grow?p.min??12:p.w,height:1,overflow:"hidden",children:$jsx("text",{ref:node,wrapMode:"none",children:p.bold?$jsx("span",{fg:fg2,children:$jsx("strong",{children:body})}):$jsx("span",{fg:fg2,children:body})})})},GAP=" ";var import_react49=__toESM(require_react_production(),1);var Ticker=(p)=>{let ref=import_react49.useRef(null),animate=exports_preferences.get("animations")!==!1&&p.active,speed=p.speed??180,hold=p.hold??600,endHold=p.endHold??3000;return import_react49.useEffect(()=>{let node=ref.current;if(!node)return;if(!animate){node.scrollX=0;return}let dir=1,tick2,wait,step=()=>{let max=node.maxScrollX;if(max<=0)return;if(node.scrollX=Math.max(0,Math.min(max,node.scrollX+dir)),!(dir>0?node.scrollX>=max:node.scrollX<=0))return;if(tick2)clearInterval(tick2),tick2=void 0;dir=-dir,wait=setTimeout(()=>{tick2=setInterval(step,speed)},endHold)};return wait=setTimeout(()=>{tick2=setInterval(step,speed)},hold),()=>{if(wait)clearTimeout(wait);if(tick2)clearInterval(tick2);if(ref.current)ref.current.scrollX=0}},[animate,speed,hold,endHold]),$jsx("box",{flexGrow:1,flexShrink:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{ref,wrapMode:"none",fg:p.fg,children:p.children})})},RX=/(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|((?<![\w*])\*[^*\s][^*]*\*(?![\w*]))|((?<!\w)_[^_\s][^_]*_(?!\w))/g,inline=(s)=>{let out=[],last=0;for(let m2 of s.matchAll(RX)){let at=m2.index??0;if(at>last)out.push({t:s.slice(last,at)});let hit=m2[0];if(hit.startsWith("`"))out.push({t:hit.slice(1,-1),c:!0});else if(hit.startsWith("**")||hit.startsWith("__"))out.push({t:hit.slice(2,-2),b:!0});else out.push({t:hit.slice(1,-1),i:!0});last=at+hit.length}if(last<s.length)out.push({t:s.slice(last)});return out.map((seg)=>seg.c?seg:{...seg,t:seg.t.replace(/^#{1,6}\s+/,"")})};var import_react50=__toESM(require_react_production(),1);var cycle=(t2)=>t2==="off"?"in":t2==="in"?"ex":"off",FilterChip=import_react50.memo((p)=>{let theme=useTheme().theme,color=p.color??theme.accent,text3=p.textColor??theme.text,bg2=p.state==="in"?color:p.state==="ex"?void 0:theme.backgroundElement,fg2=p.state==="in"?theme.background:p.state==="ex"?p.selected?color:theme.borderSubtle:p.selected?color:text3;return $jsx("box",{id:p.id,height:1,flexShrink:0,marginLeft:p.gap??1,paddingLeft:1,paddingRight:1,backgroundColor:bg2,onMouseDown:p.onMouseDown,children:$jsx("text",{fg:fg2,attributes:p.state==="ex"?TextAttributes.STRIKETHROUGH:TextAttributes.NONE,children:p.label})})});var Confirm=(props)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.onConfirm();if(keys.match("dialog.deny",key3))return props.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:props.danger?theme.warning:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}/${keys.print("dialog.accept")}] ${props.yes??"confirm"} [${keys.print("dialog.deny")}] ${props.no??"cancel"}`})})]})};function openConfirm(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Confirm,{...opts,onConfirm:()=>done(!0),onCancel:()=>done(!1)}),()=>resolve4(!1))})}var SaveDiscard=(props)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="s")return props.onPick("save");if(key3.name==="d")return props.onPick("discard");if(key3.name==="return")return props.onPick("save")}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:props.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[S/Enter] save [D] discard [Esc] keep editing"})})]})};function openSaveDiscard(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(SaveDiscard,{...opts,onPick:done,onCancel:()=>done(null)}),()=>resolve4(null))})}var import_react52=__toESM(require_react_production(),1);var TextPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react52.useState(props.initial??"");return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter confirm \xB7 Esc cancel \xB7 Ctrl+U clear":"Esc cancel"})})]})};function openTextPrompt(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(TextPrompt,{title:opts.title,label:opts.label,initial:opts.initial,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var h12=()=>exports_preferences.get("timeFormat")==="12h",abs=()=>exports_preferences.get("timeStyle")==="absolute",trunc5=(s,max)=>s.length<=max?s:s.slice(0,max-1)+"\u2026",fmt=(n)=>n>=1e6?`${(n/1e6).toFixed(2)}M`:n>=1000?`${(n/1000).toFixed(1)}k`:String(n),cost2=(c)=>c==null?"\u2014":`$${c.toFixed(2)}`,clock=(d2)=>d2.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:h12()}),stamp=(ts)=>{let d2=new Date(ts*1000);return d2.toDateString()===new Date().toDateString()?clock(d2):d2.toLocaleDateString(void 0,{month:"short",day:"numeric"})},rel=(ts)=>{let s=Math.floor(Date.now()/1000-ts);if(s<60)return"just now";if(s<3600)return`${Math.floor(s/60)}m ago`;if(s<86400)return`${Math.floor(s/3600)}h ago`;return`${Math.floor(s/86400)}d ago`},ago=(ts)=>abs()?stamp(ts):rel(ts),until=(ts)=>{if(abs())return ts<=Date.now()/1000?"due":stamp(ts);let s=Math.floor(ts-Date.now()/1000);if(s<=0)return"due";if(s<60)return`in ${s}s`;if(s<3600)return`in ${Math.floor(s/60)}m`;if(s<86400)return`in ${Math.floor(s/3600)}h`;return`in ${Math.floor(s/86400)}d`},when=(ts)=>{let d2=new Date(ts*1000);return`${d2.toLocaleDateString()} ${clock(d2)}`},span=(start,end)=>{let s=Math.round(end-start);if(s<0)return"\u2014";if(s>=3600)return`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`;if(s>=60)return`${Math.floor(s/60)}m`;return`${s}s`},dur2=(s)=>s>=3600?`${Math.floor(s/3600)}h${Math.floor(s%3600/60)}m`:s>=60?`${Math.floor(s/60)}m${Math.floor(s%60)}s`:`${Math.floor(s)}s`;var import_react53=__toESM(require_react_production(),1);import{watch as watch2,existsSync as existsSync13,statSync as statSync3}from"fs";import{dirname as dirname8,basename as basename9}from"path";import{readdir as readdir2,stat}from"fs/promises";import{openSync,readSync,closeSync,readdirSync as readdirSync4,readFileSync as readFileSync6,existsSync as existsSync12}from"fs";import{homedir as homedir5}from"os";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit=require_visit();var $Composer=composer.Composer,$Document=Document.Document,$Schema=Schema.Schema,$YAMLError=errors.YAMLError,$YAMLParseError=errors.YAMLParseError,$YAMLWarning=errors.YAMLWarning,$Alias=Alias.Alias,$isAlias=identity.isAlias,$isCollection=identity.isCollection,$isDocument=identity.isDocument,$isMap=identity.isMap,$isNode=identity.isNode,$isPair=identity.isPair,$isScalar=identity.isScalar,$isSeq=identity.isSeq,$Pair=Pair.Pair,$Scalar=Scalar.Scalar,$YAMLMap=YAMLMap.YAMLMap,$YAMLSeq=YAMLSeq.YAMLSeq;var $Lexer=lexer.Lexer,$LineCounter=lineCounter.LineCounter,$Parser=parser.Parser,$parse=publicApi.parse,$parseAllDocuments=publicApi.parseAllDocuments,$parseDocument=publicApi.parseDocument,$stringify=publicApi.stringify,$visit=visit.visit,$visitAsync=visit.visitAsync;init_sessions_db();var HOME3=process.env.HOME||homedir5(),home={path:process.env.HERMES_HOME||`${HOME3}/.hermes`},setHome2=(h2)=>{home.path=h2},hermesPath=(relative4)=>`${home.path}/${relative4}`,managedSystem=async()=>{let env2=(process.env.HERMES_MANAGED??"").trim();if(env2){let norm=env2.toLowerCase();if(norm==="1"||norm==="true"||norm==="yes"||norm==="on")return"NixOS";return{homebrew:"Homebrew",nix:"NixOS",nixos:"NixOS"}[norm]??env2}return await Bun.file(hermesPath(".managed")).exists()?"NixOS":null},makeSource=(relative4,label)=>({file:hermesPath(relative4),relative:relative4,label:label??relative4.split("/").pop()??relative4});function readSkillFrontmatter(source){try{let fd=openSync(source.file,"r"),buf=Buffer.alloc(2048),n=readSync(fd,buf,0,2048,0);closeSync(fd);let head=buf.toString("utf-8",0,n);if(!head.startsWith("---"))return{description:"",tags:[]};let end=head.indexOf(`
|
|
4104
4103
|
---`,3);if(end<0)return{description:"",tags:[]};let fm=$parse(head.slice(3,end)),tags=Array.isArray(fm.tags)?fm.tags.map(String):[];return{description:String(fm.description??""),tags}}catch{return{description:"",tags:[]}}}async function readSkillUsage(){try{let f=Bun.file(hermesPath("skills/.usage.json"));if(!await f.exists())return{};let raw=await f.json(),out={};for(let[k2,v2]of Object.entries(raw??{}))out[k2]={use_count:Number(v2.use_count??0),view_count:Number(v2.view_count??0),patch_count:Number(v2.patch_count??0),last_used_at:v2.last_used_at??null,last_viewed_at:v2.last_viewed_at??null,last_patched_at:v2.last_patched_at??null,created_at:v2.created_at??null,archived_at:v2.archived_at??null,state:v2.state??"active",pinned:Boolean(v2.pinned)};return out}catch{return{}}}async function readCuratorState(){try{let f=Bun.file(hermesPath("skills/.curator_state"));if(!await f.exists())return null;let raw=await f.json();return{last_run_at:raw.last_run_at??null,last_run_duration_seconds:raw.last_run_duration_seconds??null,last_run_summary:raw.last_run_summary??null,paused:Boolean(raw.paused),run_count:Number(raw.run_count??0)}}catch{return null}}async function readLatestCuratorReport(){try{let base2=hermesPath("logs/curator"),entries2=readdirSync4(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory());if(entries2.length===0)return null;entries2.sort((a,b2)=>b2.name.localeCompare(a.name));let runId=entries2[0].name,rel2=`logs/curator/${runId}/REPORT.md`,source=makeSource(rel2),body=await Bun.file(source.file).text();return{source,content:body.trim(),runId}}catch{return null}}function listCuratorRuns(){try{let base2=hermesPath("logs/curator");return readdirSync4(base2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).sort((a,b2)=>b2.name.localeCompare(a.name)).flatMap((e)=>{try{let fd=openSync(`${base2}/${e.name}/run.json`,"r"),buf=Buffer.alloc(8192),n=readSync(fd,buf);closeSync(fd);let j2=JSON.parse(buf.toString("utf8",0,n)),c=j2.counts??{};return[{id:e.name,at:Date.parse(j2.started_at??"")/1000||0,archived:c.archived_this_run??0,consolidated:c.consolidated_this_run??0,added:c.added_this_run??0,before:c.before??0,after:c.after??0}]}catch{return[]}})}catch{return[]}}async function readCuratorReport(id){try{return(await Bun.file(hermesPath(`logs/curator/${id}/REPORT.md`)).text()).trim()}catch{return""}}function indexCuratorLineage(){let out=new Map,push2=(name,ev)=>{let a=out.get(name)??[];a.push(ev),out.set(name,a)};try{let base2=hermesPath("logs/curator");for(let e of readdirSync4(base2,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let j2=JSON.parse(readFileSync6(`${base2}/${e.name}/run.json`,"utf8")),at=Date.parse(j2.started_at??"")/1000||0,run=e.name,into=new Map;for(let c of j2.consolidated??[])push2(c.name,{kind:"merged",run,at,into:c.into,reason:c.reason}),into.set(c.into,[...into.get(c.into)??[],c.name]);for(let[tgt,srcs]of into)push2(tgt,{kind:"absorbed",run,at,sources:srcs});for(let t2 of j2.state_transitions??[])push2(t2.name,{kind:"transition",run,at,from:t2.from,to:t2.to});for(let p of j2.pruned??[])push2(p.name,{kind:"pruned",run,at,reason:p.reason});for(let n of j2.added??[])push2(n,{kind:"added",run,at})}catch{}}}catch{}for(let a of out.values())a.sort((x2,y2)=>y2.at-x2.at);return out}function readChangelog(){try{let source=makeSource("herm/changelog.md"),fd=openSync(source.file,"r"),buf=Buffer.alloc(4096),n=readSync(fd,buf);closeSync(fd);let body=buf.toString("utf8",0,n).trim(),line=body.split(`
|
|
4105
4104
|
`).find((l)=>/^[-*\u00B7]/.test(l.trim()));return{source,headline:line?.replace(/^[-*\u00B7]\s*/,"").trim()??"",body}}catch{return null}}async function readConfig(){try{let text3=await Bun.file(hermesPath("config.yaml")).text(),raw=$parse(text3);return{source:makeSource("config.yaml","config.yaml"),model:{default:raw?.model?.default??"unknown",provider:raw?.model?.provider??"auto",base_url:raw?.model?.base_url??"",context_length:raw?.model?.context_length},agent:{max_turns:raw?.agent?.max_turns??60,reasoning_effort:raw?.agent?.reasoning_effort??"medium"},compression:{enabled:raw?.compression?.enabled??!0,threshold:raw?.compression?.threshold??0.5,target_ratio:raw?.compression?.target_ratio??0.2,protect_last_n:raw?.compression?.protect_last_n??20,summary_model:raw?.compression?.summary_model??""},memory:{memory_enabled:raw?.memory?.memory_enabled??!0,user_profile_enabled:raw?.memory?.user_profile_enabled??!0,memory_char_limit:raw?.memory?.memory_char_limit??2200,user_char_limit:raw?.memory?.user_char_limit??1375,provider:raw?.memory?.provider??"",nudge_interval:raw?.memory?.nudge_interval??10,flush_min_turns:raw?.memory?.flush_min_turns??6},display:{personality:raw?.display?.personality??"default",skin:raw?.display?.skin??"default",show_cost:raw?.display?.show_cost??!1},curator:{enabled:raw?.curator?.enabled??!0,interval_hours:raw?.curator?.interval_hours??168,stale_after_days:raw?.curator?.stale_after_days??30,archive_after_days:raw?.curator?.archive_after_days??90},approvals:{destructive_slash_confirm:raw?.approvals?.destructive_slash_confirm??!0},gateway:{platforms:{api_server:raw?.gateway?.platforms?.api_server??void 0}}}}catch{return null}}async function readMemoryFile(filename,charLimit){try{let relative4=`memories/${filename}`,content=await Bun.file(hermesPath(relative4)).text(),entryCount=content.split("\xA7").filter((s)=>s.trim()).length;return{source:makeSource(relative4,filename),content,charCount:content.length,charLimit,usagePercent:charLimit>0?Math.round(content.length/charLimit*100):0,entryCount}}catch{return null}}async function readLiveSessions(){try{let file=Bun.file(hermesPath("sessions/sessions.json"));if(!await file.exists())return{};let text3=await file.text();return JSON.parse(text3)}catch{return{}}}var MEMORY_CFG_FILES={mem0:["mem0.json"],honcho:["honcho.json"],hindsight:["hindsight/config.json"],supermemory:["supermemory.json"],holographic:["holographic.db"]};function discoverMemoryProviders(){let names=new Set(["builtin"]);try{for(let e of readdirSync4(hermesPath("hermes-agent/plugins/memory"),{withFileTypes:!0}))if(e.isDirectory()&&!e.name.startsWith("_"))names.add(e.name)}catch{}return[...names]}async function readMemoryProviders(activeProvider){let out=[];for(let name of discoverMemoryProviders()){if(name==="builtin"){out.push({name,active:!0,config:{}});continue}let cfg={};for(let f of MEMORY_CFG_FILES[name]??[])try{let file=Bun.file(hermesPath(f));if(f.endsWith(".json")){let raw=await file.json();for(let[k2,v2]of Object.entries(raw))if(typeof v2==="string"||typeof v2==="number"||typeof v2==="boolean"){let lower=k2.toLowerCase();if(lower.includes("key")||lower.includes("token")||lower.includes("secret"))cfg[k2]=typeof v2==="string"?`${v2.slice(0,4)}...`:v2;else cfg[k2]=v2}}else{let st=await file.stat();if(st)cfg.db_size=`${Math.round(st.size/1024)}KB`}}catch{}out.push({name,active:name===activeProvider,config:cfg})}return out}async function readSoul(){try{let text3=await Bun.file(hermesPath("SOUL.md")).text();return{source:makeSource("SOUL.md"),charCount:text3.length,tokenEstimate:count2(text3),content:text3}}catch{return null}}async function readToolsFromLatestSession(){try{let dir=hermesPath("sessions");if(!existsSync12(dir))return null;let glob=new Bun.Glob("session_*.json"),latestPath="",latestTime=0;for await(let path7 of glob.scan({cwd:dir})){let stat2=await Bun.file(hermesPath(`sessions/${path7}`)).stat();if(stat2&&stat2.mtimeMs>latestTime)latestTime=stat2.mtimeMs,latestPath=path7}if(!latestPath)return null;let relative4=`sessions/${latestPath}`,tools=((await Bun.file(hermesPath(relative4)).json()).tools||[]).map((t2)=>({name:t2?.function?.name??"unknown",descriptionLength:(t2?.function?.description??"").length,paramsLength:JSON.stringify(t2?.function?.parameters??{}).length}));return{source:makeSource(relative4,latestPath),tools}}catch{return null}}async function readCronOutput(jobId,tailLines=40){let dir=hermesPath(`cron/output/${jobId}`),entries2;try{entries2=await readdir2(dir)}catch{return null}let md=entries2.filter((f)=>f.endsWith(".md")).sort().reverse();if(md.length===0)return null;let path7=`${dir}/${md[0]}`,full=await Bun.file(path7).text(),lines3=full.trimEnd().split(`
|
|
4106
4105
|
`),text3=lines3.length>tailLines?`\u2026(${lines3.length-tailLines} earlier lines)
|
|
@@ -4121,7 +4120,7 @@ Current chat will be replaced.`,yes:"load"}).then((ok)=>{if(ok)l.onSwitch?.(sid2
|
|
|
4121
4120
|
`,skE);while(end<text3.length&&end>=0){let nl=text3.indexOf(`
|
|
4122
4121
|
`,end+1);if(nl<0){end=text3.length;break}let line2=text3.slice(end+1,nl).trim();if(line2.startsWith("#"))break;if(line2===""){if(text3.slice(nl+1,text3.indexOf(`
|
|
4123
4122
|
`,nl+1)).trim().startsWith("#")){end=nl;break}}end=nl}mark2(skH,end+1,"skills","Skills Catalog",makeSource("skills","skills/"))}let proj=text3.indexOf("# Project Context");if(proj>=0){let conv2=text3.indexOf("Conversation started:");mark2(proj,conv2>proj?conv2:text3.length,"project","Project Context",makeSource("AGENTS.md"))}let conv=text3.indexOf("Conversation started:");if(conv>=0)mark2(conv,text3.length,"meta","Session Metadata");let start=-1;for(let i=0;i<=text3.length;i++)if(i<text3.length&&!used[i]){if(start<0)start=i}else if(start>=0){let slice=text3.slice(start,i);if(slice.trim().length>0)sections.push({id:"other",label:"Other",chars:slice.length,tokens:count2(slice),text:slice});start=-1}return sections.sort((a,b2)=>text3.indexOf(a.text)-text3.indexOf(b2.text))}function classifyTools(tools){let system=[],mcp=[];for(let t2 of tools)if(t2.name.startsWith("mcp_"))mcp.push(t2);else system.push(t2);return{system,mcp}}function toolTokens(tool){return Math.ceil((tool.descriptionLength+tool.paramsLength)/CPT)}function build(opts){let pct=(t2)=>opts.contextLength>0?t2/opts.contextLength*100:0,result=[],byId2=new Map;for(let s of opts.sections)byId2.set(s.id,s);let promptChildren=opts.sections.filter((sec)=>SYSTEM_PROMPT_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),promptTok=promptChildren.reduce((s,c)=>s+c.tokens,0);if(promptTok>0)result.push({id:"system_prompt",label:"System Prompt",tokens:promptTok,percent:pct(promptTok),children:promptChildren});let{system:sysTools,mcp:mcpTools}=classifyTools(opts.tools),sysToolsTok=sysTools.reduce((s,t2)=>s+toolTokens(t2),0);if(sysToolsTok>0)result.push({id:"system_tools",label:"System Tools",tokens:sysToolsTok,percent:pct(sysToolsTok)});let mcpToolsTok=mcpTools.reduce((s,t2)=>s+toolTokens(t2),0);if(mcpToolsTok>0)result.push({id:"mcp_tools",label:"MCP Tools",tokens:mcpToolsTok,percent:pct(mcpToolsTok)});let memChildren=opts.sections.filter((sec)=>MEMORY_IDS.has(sec.id)&&sec.tokens>0).map((sec)=>({id:sec.id,label:sec.label,tokens:sec.tokens,percent:pct(sec.tokens),section:sec})),memTok=memChildren.reduce((s,c)=>s+c.tokens,0);if(memTok>0)result.push({id:"memory",label:"Memory",tokens:memTok,percent:pct(memTok),children:memChildren});let skillsSec=byId2.get("skills"),skillsTok=skillsSec?.tokens??opts.skillsTokens??0;if(skillsTok>0)result.push({id:"skills",label:"Skills",tokens:skillsTok,percent:pct(skillsTok),section:skillsSec});if(opts.conversationTokens>0){let ct=opts.conversationTokens;result.push({id:"conversation",label:"~Conversation",tokens:ct,percent:pct(ct)})}let taken=result.reduce((s,g)=>s+g.tokens,0),used=opts.usedTokens;if(typeof used!=="number"){let unknown2=Math.max(0,opts.contextLength-taken);if(unknown2>0)result.push({id:"unknown",label:"Unknown (live unavailable)",tokens:unknown2,percent:pct(unknown2)});return result}let unknown=Math.max(0,used-taken);if(unknown>0)result.push({id:"unknown",label:"Unknown / Provider Overhead",tokens:unknown,percent:pct(unknown)});let overage=Math.max(0,taken-used);if(overage>0)result.push({id:"overage",label:"Estimate Overage",tokens:overage,percent:pct(overage)});let free=Math.max(0,opts.contextLength-used);return result.push({id:"free",label:"Free",tokens:free,percent:pct(free)}),result}function drill(group2){if(!group2.children||group2.children.length===0)return[];let total=group2.tokens;return group2.children.map((c)=>({...c,percent:total>0?c.tokens/total*100:0}))}function cells(segments,fallback="free"){let filled=segments.flatMap((seg)=>Array.from({length:Math.round(seg.percent/100*GRID)},()=>({id:seg.id}))),pad=Array.from({length:Math.max(0,GRID-filled.length)},()=>({id:fallback}));return[...filled,...pad].slice(0,GRID)}var import_react56=__toESM(require_react_production(),1);var FileLink=import_react56.memo(({source,children:children2})=>{let theme=useTheme().theme,[hovered,setHovered]=import_react56.useState(!1);return $jsx("box",{height:1,onMouseDown:()=>openFile(source.file),onMouseOver:()=>setHovered(!0),onMouseOut:()=>setHovered(!1),children:$jsx("text",{fg:theme.info,attributes:hovered?TextAttributes.UNDERLINE:TextAttributes.NONE,children:children2??source.label})})}),KVLink=(props)=>{let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:13,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:props.label})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx(FileLink,{source:props.source,children:props.text??props.source.label})})]})};var GOLDEN_ANGLE=137.50776405003785;function luminance(c){return 0.299*c.r+0.587*c.g+0.114*c.b}function rgbaToHsl(c){let{r,g,b:b2}=c,max=Math.max(r,g,b2),min=Math.min(r,g,b2),l=(max+min)/2,d2=max-min;if(d2===0)return[0,0,l];let s=l>0.5?d2/(2-max-min):d2/(max+min),h2;switch(max){case r:h2=(g-b2)/d2+(g<b2?6:0);break;case g:h2=(b2-r)/d2+2;break;default:h2=(r-g)/d2+4}return[h2*60,s,l]}function hslToRgba(h2,s,l){if(h2=(h2%360+360)%360/360,s===0)return RGBA.fromValues(l,l,l,1);let q3=l<0.5?l*(1+s):l+s-l*s,p=2*l-q3,ch=(t2)=>{if(t2<0)t2+=1;if(t2>1)t2-=1;if(t2<0.16666666666666666)return p+(q3-p)*6*t2;if(t2<0.5)return q3;if(t2<0.6666666666666666)return p+(q3-p)*(0.6666666666666666-t2)*6;return p};return RGBA.fromValues(ch(h2+0.3333333333333333),ch(h2),ch(h2-0.3333333333333333),1)}function categorical(seed,bg2,n){let[h0]=rgbaToHsl(seed),dark=luminance(bg2)<0.5,s=dark?0.6:0.7,l=dark?0.62:0.42,out=[];for(let i=0;i<n;i++)out.push(hslToRgba(h0+i*GOLDEN_ANGLE,s,l));return out}var DEFAULT_CTX=128000,COLS2=16,SLOTS2=["system_prompt","system_tools","mcp_tools","memory","skills","conversation","soul","mem0","user","project","meta","other","unknown","overage"],SLOT=Object.fromEntries(SLOTS2.map((id,i)=>[id,i])),rampCache=new WeakMap;function ramp2(theme){let r=rampCache.get(theme);if(!r)rampCache.set(theme,r=categorical(theme.primary,theme.background,SLOTS2.length));return r}function clr(id,theme){if(id==="free")return theme.borderSubtle;return ramp2(theme)[SLOT[id]??SLOT.other]}var fmt2=(n)=>{if(n>=1e6)return`${(n/1e6).toFixed(1)}M`;if(n>=1e4)return`${Math.round(n/1000)}k`;if(n>=1000)return`${(n/1000).toFixed(1)}k`;return String(n)},est=(s)=>s?count2(s):0,bar=(pct,w2=20)=>{let f=Math.round(Math.max(0,Math.min(100,pct))/100*w2);return`[${"\u2588".repeat(f)}${"\u2591".repeat(Math.max(0,w2-f))}]`},SectionPanel=import_react57.memo(({seg,theme})=>{let{syntaxStyle}=useTheme(),sec=seg.section;if(!sec)return null;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsxs("text",{children:[sec.chars.toLocaleString()," chars \xB7 ~",fmt2(sec.tokens)," tokens"]}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsx("markdown",{content:sec.text,fg:theme.markdownText,syntaxStyle})]})}),MemoryPanel=import_react57.memo(({seg,theme,label:label2,chars,limit,pct,entries:entries2,source})=>$jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(seg.id,theme),children:"\u25FC"})," ",seg.label," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:$jsx("strong",{children:label2})}),source?$jsxs($Fragment,{children:[$jsx("text",{children:" ("}),$jsx(FileLink,{source}),$jsx("text",{children:")"})]}):null]}),$jsxs("text",{children:[chars.toLocaleString()," / ",limit.toLocaleString()," chars (",pct,"%)"]}),$jsxs("text",{children:[bar(pct,25),pct>=95?" \u26A0 near limit":""]}),$jsx("text",{children:" "}),$jsxs("text",{children:[entries2.length," entries:"]}),entries2.map((e,i)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",e]},i))]})),SkillsPanel=import_react57.memo(({seg,theme})=>{let sec=seg.section;if(!sec)return null;let cats={};for(let line2 of sec.text.split(`
|
|
4124
|
-
`)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react57.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label2=kind2==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind2==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind2,theme),children:"\u25FC"})," ",label2," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react57.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react57.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),toolsFromInfo=(info)=>{if(!info||info.tools===void 0)return null;let tools=Object.entries(info.tools).flatMap(([group2,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group2.length})));return{source:makeSource("state.db","session.info"),tools}},configuredContextLength=(config)=>{let n=config?.model?.context_length;return typeof n==="number"&&n>0?n:void 0},contextMeter=(usage,info,config)=>({max:usage?.context_max??info?.usage?.context_max??info?.context_max??configuredContextLength(config)??DEFAULT_CTX,used:usage?.context_used??info?.usage?.context_used??info?.context_used}),Context=import_react57.memo(({messages=NO_MESSAGES,info,usage,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),[wire,setWire]=import_react57.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react57.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react57.useState(null),[selected,setSelected]=import_react57.useState(null),[drilled,setDrilled]=import_react57.useState(null);import_react57.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let meter=contextMeter(usage,info,config??null),ctxLen=meter.max,used=meter.used,reliable=typeof used==="number",output=wire.output,pct=reliable&&ctxLen>0?Math.round(used/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react57.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react57.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react57.useMemo(()=>{let liveTools=toolsFromInfo(info);if(liveTools)return liveTools;if(info?.tools!==void 0)return liveTools;return toolsInfo},[info,toolsInfo]),top=import_react57.useMemo(()=>build({contextLength:ctxLen,usedTokens:used,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,used,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react57.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":reliable?"free":"unknown"),[view,drilledGroup,reliable]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react57.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react57.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react57.useRef(0),segs=view.filter((s)=>s.tokens>0),idx=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key3)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key3,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key3.name==="right")return setSel((p)=>p+1);if(key3.name==="left")return setSel((p)=>p-1);if(key3.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&¤tTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&¤tTools){let{mcp}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):reliable?$jsx("span",{fg:theme.info,children:" (click group to expand)"}):$jsxs("span",{fg:theme.warning,children:[" \xB7 live usage unavailable \xB7 limit ",fmt2(ctxLen)]})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,reliable&&!drilled?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})}):null]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:reliable?"\u2191\u2193 nav \xB7 click a group to drill in":"live usage unavailable \xB7 estimates shown with ~",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:reliable?`Context \xB7 ${fmt2(used)} / ${fmt2(ctxLen)} (${pct}%)`:`Context \xB7 live usage unavailable \xB7 limit ${fmt2(ctxLen)}`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[!drilled&&compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row3)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row3*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=!drilled&&row3*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row3))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react59=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react59.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost2(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react59.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc5(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react59.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react59.useState(7),[data2,setData]=import_react59.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react59.useState(()=>cache3.get(days)?.byTool??null),[tick3,setTick]=import_react59.useState(0),gen=import_react59.useRef(0);import_react59.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick3]);let keys=useKeys();useKeyboard((key3)=>{if(!props.focused)return;if(keys.match("list.refresh",key3))return cache3.delete(days),setTick((n)=>n+1);if(key3.raw==="1")return setDays(1);if(key3.raw==="7")return setDays(7);if(key3.raw==="3")return setDays(30);if(key3.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react59.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost2(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc5(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost2(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react61=__toESM(require_react_production(),1);var SubTabBar=import_react61.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & gallery"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Gallery","Studio","Marketplace"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},studio:{tab:4,sub:1},gallery:{tab:4,sub:0},marketplace:{tab:4,sub:2}};var SessionsGroup=import_react62.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react62.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react74=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react65=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react63.useState(""),[cursor,setCursor]=import_react63.useState(0),mode=import_react63.useRef("kb"),moved=import_react63.useRef(!1),sb=import_react63.useRef(null),theme=useTheme().theme,opts=import_react63.useMemo(()=>props.options.map((o)=>({name:`${props.current==null?"":o.value===props.current?"\u25CF ":" "}${o.title}`,description:o.hint?[o.description,o.hint].filter(Boolean).join(" \u2014 "):o.description??"",value:o.value})),[props.current,props.options]),sel=props.current==null?0:Math.max(0,props.options.findIndex((o)=>o.value===props.current)),desc=props.options.some((o)=>!!o.description||!!o.hint),filtered=import_react63.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react63.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react63.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react63.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react63.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key3)=>{if(!filterable)return;if(handleListKey(keys,key3,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)}}))return;if(props.onKey?.(key3))return});let idx=0,entries2=Array.from(groups.entries());if(!filterable)return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),$jsx("select",{focused:!0,width:58,height:Math.min(16,Math.max(1,props.options.length*(desc?2:1))),options:opts,selectedIndex:sel,showDescription:desc,showScrollIndicator:props.options.length>8,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,fastScrollStep:Math.max(1,props.options.length),keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"pageup",action:"move-up-fast"},{name:"pagedown",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"}],onChange:(i)=>{let item=props.options[i];if(item&&props.onMove)props.onMove(item)},onSelect:(i)=>{let item=props.options[i];if(item)props.onSelect(item)}}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]});return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react65.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react65.useRef(new Map),enabled2=import_react65.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react65.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react65.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react65.useCallback((val)=>{enabled2.current=val},[]),open2=import_react65.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key3)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key3))return open2();for(let c of all())if(c.action&&keys.match(c.action,key3))return c.onSelect()});let value=import_react65.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react68=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react68.useState(!1);useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.deny",key3))return props.done(null);if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.done(force);if(key3.name==="space"||key3.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react70=__toESM(require_react_production(),1);import{existsSync as existsSync14,readFileSync as readFileSync7}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename10,dirname as dirname9}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname9(hh);return basename10(parent2)==="profiles"?dirname9(parent2):hh}function profileNameFrom(hh){let parent2=dirname9(hh);return basename10(parent2)==="profiles"?basename10(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync7(join11(root(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function readModel(dir){try{let raw=readFileSync7(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean3=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean3(m2),clean3(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync7(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync7(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join11(dir,"distribution.yaml");if(!existsSync14(path7))return null;let data2=(()=>{try{return $parse(readFileSync7(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync14(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync14(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync14(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync14(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync7(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename10(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync14(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync14(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react70.useState(""),[cloneIdx,setCloneIdx]=import_react70.useState(0),[alias,setAlias]=import_react70.useState(!0),[field,setField]=import_react70.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key3)=>{if(key3.name==="escape")return done(null);if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="return")return submit2();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[a-z0-9_-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(field==="clone"){if(key3.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key3.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key3.name==="space"||key3.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react72=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir2}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync2(join12(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest2=readDistributionManifest(tmp);if(!manifest2){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest2,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react72.useState("");return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.accept",key3)||keys.match("dialog.cancel",key3))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react72.useState(""),[alias,setAlias]=import_react72.useState(!1),[field,setField]=import_react72.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel();if(key3.name==="tab")return move(key3.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key3))return fire();if(field==="alias"&&(key3.name==="space"||key3.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react74.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react74.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react74.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react74.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react74.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react74.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react74.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react74.useState("profiles"),[pView,setPView]=import_react74.useState("list"),[profiles,setProfiles]=import_react74.useState([]),[deleg,setDeleg]=import_react74.useState(null),[liveMap,setLiveMap]=import_react74.useState(()=>new Map),[now,setNow]=import_react74.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react74.useState(0),[dSel,setDSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react74.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react74.useRef(void 0),[stats,setStats]=import_react74.useState(()=>new Map),[sticky,setSticky]=import_react74.useState(stickyDefault),loadProfiles=import_react74.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react74.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react74.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react74.useEffect(loadDeleg,[loadDeleg]),import_react74.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react74.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react74.useCallback((i)=>setPSel(i),[]),dHover=import_react74.useCallback((i)=>setDSel(i),[]),pDelete=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4123
|
+
`)){if(line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)){let cat=line2.match(/^\s{2}(\S[\w-]*(?:\/\S+)?):\s/)[1];if(!cats[cat])cats[cat]=0}if(line2.match(/^\s{4}- \S+:/)){let last2=Object.keys(cats).pop();if(last2)cats[last2]++}}let sorted=Object.entries(cats).sort((a,b2)=>b2[1]-a[1]),total=sorted.reduce((s,[,n])=>s+n,0);return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("skills",theme),children:"\u25FC"})," Skills Catalog \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),sec.source?$jsxs("box",{flexDirection:"row",height:1,children:[$jsx("text",{children:"Source: "}),$jsx(FileLink,{source:sec.source})]}):null,$jsx("text",{children:" "}),$jsxs("text",{children:[total," skills in ",sorted.length," categories \xB7 ",sec.chars.toLocaleString()," chars"]}),$jsx("text",{fg:theme.textMuted,children:"Largest context section \u2014 skill names + descriptions injected every turn."}),$jsx("text",{children:" "}),sorted.map(([cat,n])=>$jsxs("text",{fg:theme.text,children:["\xB7 ",cat," (",n,")"]},cat))]})}),ToolsPanel=import_react57.memo(({seg,theme,tools,kind:kind2})=>{let sorted=[...tools].sort((a,b2)=>b2.descriptionLength+b2.paramsLength-(a.descriptionLength+a.paramsLength)),label2=kind2==="mcp_tools"?"MCP Tools":"System Tools",blurb=kind2==="mcp_tools"?"MCP-loaded tools \u2014 schemas injected via mcp_ prefix.":"Built-in tool schemas sent with every API call.";return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr(kind2,theme),children:"\u25FC"})," ",label2," \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:[tools.length," tools \u2014 ",blurb]}),$jsx("text",{children:" "}),sorted.map((t2)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",t2.name," (",fmt2(toolTokens(t2))," tok)"]},t2.name))]})}),ConvPanel=import_react57.memo(({seg,theme,messages,output})=>{let user=messages.filter((m2)=>m2.role==="user"),asst=messages.filter((m2)=>m2.role==="assistant"),non=messages.filter((m2)=>m2.role!=="system");return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("conversation",theme),children:"\u25FC"})," Conversation \u2014 ",fmt2(seg.tokens)," tokens (",seg.percent.toFixed(1),"%)"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["User: ",user.length," msgs (~",fmt2(est(user.map((m2)=>text(m2)).join("")))," tok)"]}),$jsxs("text",{children:["Agent: ",asst.length," msgs (~",fmt2(est(asst.map((m2)=>text(m2)).join("")))," tok)"]}),output>0?$jsxs("text",{children:["Output generated: ",fmt2(output)," tokens"]}):null,$jsx("text",{children:" "}),non.length>0?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.info,children:"Messages:"}),$jsx("text",{children:" "}),non.map((m2,i)=>$jsxs("text",{children:[$jsx("span",{fg:m2.role==="user"?theme.info:theme.success,children:m2.role==="user"?"\u25B8 You":"\u25C2 Agent"})," ","(",fmt2(est(text(m2))),") ",text(m2).replace(/\n/g," ")]},i))]}):$jsx("text",{fg:theme.warning,children:"No messages yet"})]})}),FreePanel=import_react57.memo(({seg,theme,ctxLen,comp,onEditThreshold})=>{let used=ctxLen-seg.tokens,threshold=Math.round(ctxLen*(comp?.threshold??0.5)),pct=threshold>0?Math.min(100,Math.round(used/threshold*100)):0;return $jsxs("scrollbox",{borderStyle:"single",padding:1,flexGrow:1,scrollY:!0,children:[$jsx("text",{children:$jsxs("strong",{children:[$jsx("span",{fg:clr("free",theme),children:"\u25FB"})," Free Space \u2014 ",fmt2(seg.tokens)," tokens"]})}),$jsx("text",{children:" "}),$jsxs("text",{children:["Context window: ",fmt2(ctxLen)]}),$jsxs("text",{children:["Used: ",fmt2(used)," (",Math.round(used/ctxLen*100),"%)"]}),$jsxs("text",{children:["Available: ",fmt2(seg.tokens)," (",seg.percent.toFixed(1),"%)"]}),$jsx("text",{children:" "}),comp?$jsxs($Fragment,{children:[$jsx("text",{children:$jsx("strong",{children:"Compression"})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[comp.enabled?"\u2713 Enabled":"\u2717 Disabled"," \xB7 threshold "]}),$jsx("box",{flexShrink:0,onMouseDown:onEditThreshold,children:$jsx("text",{fg:theme.info,children:$jsxs("u",{children:[Math.round(comp.threshold*100),"%"]})})}),$jsxs("text",{children:[" (",fmt2(threshold),")"]})]}),$jsxs("text",{children:[bar(pct)," ",pct,"%"]}),$jsxs("text",{children:["Protect last ",comp.protect_last_n," messages \xB7 target ratio ",Math.round(comp.target_ratio*100),"%"]}),comp.summary_model?$jsxs("text",{children:["Summary model: ",comp.summary_model]}):null]}):null]})}),NO_MESSAGES=Object.freeze([]),toolsFromInfo=(info)=>{if(!info||info.tools===void 0)return null;let tools=Object.entries(info.tools).flatMap(([group2,names])=>names.map((name)=>({name,descriptionLength:0,paramsLength:group2.length})));return{source:makeSource("state.db","session.info"),tools}},configuredContextLength=(config)=>{let n=config?.model?.context_length;return typeof n==="number"&&n>0?n:void 0},contextMeter=(usage,info,config)=>({max:usage?.context_max??info?.usage?.context_max??info?.context_max??configuredContextLength(config)??DEFAULT_CTX,used:usage?.context_used??info?.usage?.context_used??info?.context_used}),Context=import_react57.memo(({messages=NO_MESSAGES,info,usage,focused})=>{let config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),gw=useGateway(),dialog=useDialog(),toast=useToast(),systemPrompt2=useHome("systemPrompt"),toolsInfo=useHome("toolsInfo"),soul=useHome("soul"),[wire,setWire]=import_react57.useState({input:0,output:0,total:0,calls:0}),wireRef=import_react57.useRef(wire),theme=useTheme().theme,[hovered,setHovered]=import_react57.useState(null),[selected,setSelected]=import_react57.useState(null),[drilled,setDrilled]=import_react57.useState(null);import_react57.useEffect(()=>{let input=0,output2=0,total=0,calls=0;for(let m2 of messages)if(m2.usage)input+=m2.usage.input,output2+=m2.usage.output,total+=m2.usage.total,calls++;let next={input,output:output2,total,calls};wireRef.current=next,setWire(next)},[messages]);let meter=contextMeter(usage,info,config??null),ctxLen=meter.max,used=meter.used,reliable=typeof used==="number",output=wire.output,pct=reliable&&ctxLen>0?Math.round(used/ctxLen*100):0,thresholdPct=config?.compression?.threshold??0.5,thresholdIdx=Math.min(COLS2*COLS2,Math.max(0,Math.round(thresholdPct*COLS2*COLS2))),compressions=info?.usage?.compressions??0,promptText=info?.system_prompt??systemPrompt2?.text??"",sections=import_react57.useMemo(()=>parse4(promptText),[promptText]),convTok=import_react57.useMemo(()=>est(messages.filter((m2)=>m2.role!=="system").map((m2)=>text(m2)).join("")),[messages]),currentTools=import_react57.useMemo(()=>{let liveTools=toolsFromInfo(info);if(liveTools)return liveTools;if(info?.tools!==void 0)return liveTools;return toolsInfo},[info,toolsInfo]),top=import_react57.useMemo(()=>build({contextLength:ctxLen,usedTokens:used,sections,conversationTokens:convTok,tools:currentTools?.tools??[]}),[ctxLen,used,sections,convTok,currentTools]),drilledGroup=drilled?top.find((s)=>s.id===drilled):null,view=drilledGroup?drill(drilledGroup):top,grid=import_react57.useMemo(()=>cells(view,drilledGroup?drilledGroup.children?.[0]?.id??"other":reliable?"free":"unknown"),[view,drilledGroup,reliable]),findSeg=(id)=>{if(drilledGroup)return view.find((s)=>s.id===id);return top.find((s)=>s.id===id)},memEntries=import_react57.useMemo(()=>(memory?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[memory?.content]),userEntries=import_react57.useMemo(()=>(userProfile?.content??"").split("\xA7").map((s)=>s.trim()).filter(Boolean),[userProfile?.content]),click=(id)=>{if(drilled){setSelected(selected===id?null:id);return}let seg=top.find((s)=>s.id===id);if(seg?.children&&seg.children.length>0){setDrilled(id),setSelected(null);return}setSelected(selected===id?null:id)},lastEsc=import_react57.useRef(0),segs=view.filter((s)=>s.tokens>0),idx=selected?segs.findIndex((s)=>s.id===selected):-1,setSel=(v2)=>{let n=Math.max(0,Math.min(segs.length-1,typeof v2==="function"?v2(idx):v2));setSelected(segs[n]?.id??null)},keys=useKeys();useKeyboard((key3)=>{if(!focused||dialog.open())return;if(handleListKey(keys,key3,{count:segs.length,setSel,onActivate:()=>{if(drilled||!selected)return;if(top.find((s)=>s.id===selected)?.children?.length)setDrilled(selected),setSelected(null)}}))return;if(key3.name==="right")return setSel((p)=>p+1);if(key3.name==="left")return setSel((p)=>p-1);if(key3.name!=="escape")return;let now=Date.now();if(now-lastEsc.current<400){setSelected(null),setDrilled(null),lastEsc.current=0;return}if(lastEsc.current=now,selected)return setSelected(null);if(drilled)return setDrilled(null)});let editThreshold=async()=>{let cur=Math.round((config?.compression?.threshold??0.5)*100),v2=await openTextPrompt(dialog,{title:"Compression threshold",label:"Percent (10\u201395)",initial:String(cur)});if(v2===null)return;let n=Math.max(10,Math.min(95,Number(v2)||cur)),{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"compression.threshold",to:n/100}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),toast.show({variant:"success",message:`Threshold \u2192 ${n}%`})},detail=()=>{if(!selected)return null;let seg=findSeg(selected);if(!seg)return null;if(selected==="memory"&&drilled==="memory"&&memory)return $jsx(MemoryPanel,{seg,theme,label:"Agent Notes",chars:memory.charCount,limit:memory.charLimit,pct:memory.usagePercent,entries:memEntries,source:memory.source});if(selected==="user"&&userProfile)return $jsx(MemoryPanel,{seg,theme,label:"User Profile",chars:userProfile.charCount,limit:userProfile.charLimit,pct:userProfile.usagePercent,entries:userEntries,source:userProfile.source});if(selected==="skills")return $jsx(SkillsPanel,{seg,theme});if(selected==="system_tools"&¤tTools){let{system}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:system,kind:"system_tools"})}if(selected==="mcp_tools"&¤tTools){let{mcp}=classifyTools(currentTools.tools);return $jsx(ToolsPanel,{seg,theme,tools:mcp,kind:"mcp_tools"})}if(selected==="soul"&&soul){let soulSeg={...seg,section:{id:"soul",label:"SOUL.md",chars:soul.charCount,tokens:soul.tokenEstimate,text:soul.content,source:soul.source}};return $jsx(SectionPanel,{seg:soulSeg,theme})}if(selected==="conversation")return $jsx(ConvPanel,{seg,theme,messages,output});if(selected==="free")return $jsx(FreePanel,{seg,theme,ctxLen,comp:config?.compression,onEditThreshold:editThreshold});return $jsx(SectionPanel,{seg,theme})},breakdown=()=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsxs("text",{children:[$jsx("strong",{children:"Breakdown"}),drilledGroup?$jsxs("span",{fg:theme.info,children:[" \xB7 ",drilledGroup.label," (",fmt2(drilledGroup.tokens)," tok)"]}):reliable?$jsx("span",{fg:theme.info,children:" (click group to expand)"}):$jsxs("span",{fg:theme.warning,children:[" \xB7 live usage unavailable \xB7 limit ",fmt2(ctxLen)]})]}),view.filter((s)=>s.tokens>0).map((s)=>$jsxs("text",{children:[$jsx("span",{fg:clr(s.id,theme),children:s.id==="free"?"\u25FB":"\u25FC"})," ",s.label," \u2014 ",fmt2(s.tokens)," (",s.percent.toFixed(1),"%)",s.children?$jsx("span",{fg:theme.textMuted,children:" \u25B8"}):null]},s.id)),output>0&&!drilled?$jsxs("text",{children:[$jsx("span",{fg:theme.success,children:"\u25FC"})," Output \u2014 ",fmt2(output)," tokens"]}):null,reliable&&!drilled?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:["\u25FC Beyond compression threshold (",Math.round(thresholdPct*100),"%)"]})}):null]}),crumb=drilled?`${drilledGroup?.label}${selected?` \xB7 ${findSeg(selected)?.label}`:""}`:reliable?"\u2191\u2193 nav \xB7 click a group to drill in":"live usage unavailable \xB7 estimates shown with ~",escHint=selected||drilled?" \xB7 Esc back":"",focus=selected||hovered,focusSeg=focus?findSeg(focus):null;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:reliable?`Context \xB7 ${fmt2(used)} / ${fmt2(ctxLen)} (${pct}%)`:`Context \xB7 live usage unavailable \xB7 limit ${fmt2(ctxLen)}`,children:[$jsx("box",{height:1,children:focusSeg?$jsxs("text",{fg:clr(focusSeg.id,theme),children:["\u25FC ",focusSeg.label," \u2014 ",fmt2(focusSeg.tokens)," tok (",focusSeg.percent.toFixed(1),"%)"]}):$jsx("text",{children:" "})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{flexDirection:"column",marginRight:2,flexShrink:0,children:[!drilled&&compressions>0?$jsx("box",{height:1,marginBottom:1,children:$jsxs("text",{fg:theme.warning,children:["\xD7",compressions," compressed"]})}):null,$jsx("box",{border:!0,customBorderChars:CORNERS,borderColor:theme.border,children:[...Array(COLS2)].map((_2,row3)=>$jsx("box",{flexDirection:"row",height:1,children:[...Array(COLS2)].map((_3,col)=>{let cell=grid[row3*COLS2+col],hl=selected?selected===cell.id:hovered===cell.id,past=!drilled&&row3*COLS2+col>=thresholdIdx,glyph=!past&&cell.id==="free"?"\u25FB":"\u25FC";return $jsx("box",{height:1,width:2,backgroundColor:hl?clr(cell.id,theme):void 0,onMouseOver:()=>setHovered(cell.id),onMouseOut:()=>setHovered(null),onMouseDown:()=>click(cell.id),children:$jsx("text",{fg:past?theme.textMuted:clr(cell.id,theme),children:glyph})},col)})},row3))})]}),$jsx("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:selected?detail():breakdown()})]})]}),$jsx(HintBar,{raw:crumb+escHint})]})});var import_react59=__toESM(require_react_production(),1);init_hermes_analytics();var BLOCKS=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",rows2=(vals,h2)=>{let peak=Math.max(1,...vals),ticks=vals.map((v2)=>Math.round(h2*8*v2/peak));return Array.from({length:h2},(_2,r)=>{let floor=(h2-1-r)*8;return ticks.map((t2)=>BLOCKS[Math.max(0,Math.min(8,t2-floor))]).join("")})},Chart=import_react59.memo((p)=>{let theme=useTheme().theme,days=p.data.byDay,vals=days.map((d2)=>d2.cost),peak=Math.max(...vals,0.01),axis=(v2)=>cost2(v2).padStart(7),md=(s)=>s.slice(5);return $jsxs("box",{flexDirection:"column",children:[rows2(vals,p.h).map((line2,i)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:i===0?axis(peak):i===p.h-1?axis(0):""})}),$jsx("text",{fg:theme.primary,children:line2})]},i)),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,flexShrink:0}),$jsx("text",{fg:theme.textMuted,children:days.length>0?`${md(days[0].date)}${" ".repeat(Math.max(0,days.length-10))}${md(days[days.length-1].date)}`:""})]})]})}),Rank=import_react59.memo((p)=>{let theme=useTheme().theme;if(p.rows===null)return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),$jsx("box",{height:1,children:$jsx(Spinner,{label:"aggregating\u2026"})})]});let top=p.rows.slice(0,p.n??10),peak=Math.max(1,...top.map((r)=>r.n)),total=p.rows.reduce((a,r)=>a+r.n,0);return $jsxs("box",{flexDirection:"column",flexGrow:1,flexBasis:0,minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.title})}),top.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2014"})}):top.map((r)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{w:18,children:trunc5(r.name,17)}),$jsx(Col,{w:12,fg:p.fg,children:"\u2587".repeat(Math.max(1,Math.round(10*r.n/peak)))}),$jsx(Col,{w:7,right:!0,children:fmt(r.n)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:total?`${Math.round(100*r.n/total)}%`:""})]},r.name))]})}),Analytics=import_react59.memo((props)=>{let theme=useTheme().theme,dims=useTerminalDimensions(),[days,setDays]=import_react59.useState(7),[data2,setData]=import_react59.useState(()=>cache3.get(days)??null),[tools,setTools]=import_react59.useState(()=>cache3.get(days)?.byTool??null),[tick3,setTick]=import_react59.useState(0),gen=import_react59.useRef(0);import_react59.useEffect(()=>{let hit=cache3.get(days);setData(hit??null),setTools(hit?.byTool??null);let g=++gen.current;return io.analytics(days,{tools:!1}).then((fast)=>{if(gen.current!==g)return;setData(fast),io.analytics(days).then((full)=>{if(gen.current!==g)return;cache3.set(days,full),setData(full),setTools(full.byTool)})}),()=>{gen.current++}},[days,tick3]);let keys=useKeys();useKeyboard((key3)=>{if(!props.focused)return;if(keys.match("list.refresh",key3))return cache3.delete(days),setTick((n)=>n+1);if(key3.raw==="1")return setDays(1);if(key3.raw==="7")return setDays(7);if(key3.raw==="3")return setDays(30);if(key3.raw==="9")return setDays(90)});let t2=data2?.total,tok=(t2?.input??0)+(t2?.output??0),title=import_react59.useMemo(()=>!t2?`Analytics \xB7 ${days}d`:`Analytics \xB7 ${days}d \xB7 ${t2.sessions} sess \xB7 ${fmt(tok)} tok \xB7 ${cost2(t2.cost)}`,[days,t2,tok]),wide=dims.width>=110,chartH=dims.height>=40?8:6;if(!data2)return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsx("box",{height:1,children:$jsx(Spinner,{label:`aggregating ${days}d\u2026`})})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]});let nTools=8,nSrc=6,ranksH=wide?Math.max(nTools,nSrc)+1:nTools+nSrc+3;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title,children:$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,overflow:"hidden",children:[$jsxs("box",{flexShrink:0,flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`Cost per day \xB7 ${fmt(t2.input)} in \xB7 ${fmt(t2.output)} out \xB7 ${fmt(t2.cache)} cache \xB7 ${fmt(t2.calls)} tool calls`})}),$jsx(Chart,{data:data2,h:chartH})]}),$jsx("box",{height:1,flexShrink:0}),$jsx("box",{flexShrink:0,children:$jsxs(Hdr,{children:[$jsx(Col,{grow:!0,min:18,fg:theme.textMuted,children:"Model"}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:"sess"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"in"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"out"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cache"}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:"cost"})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,flexShrink:1,minHeight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:data2.byModel.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"no sessions in range"})}):data2.byModel.map((m2)=>$jsxs("box",{height:1,flexDirection:"row",children:[$jsx(Col,{grow:!0,min:18,children:trunc5(m2.model,40)}),$jsx(Col,{w:6,right:!0,fg:theme.textMuted,children:String(m2.sessions)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.input)}),$jsx(Col,{w:9,right:!0,children:fmt(m2.output)}),$jsx(Col,{w:9,right:!0,fg:theme.textMuted,children:fmt(m2.cache)}),$jsx(Col,{w:9,right:!0,fg:theme.accent,children:cost2(m2.cost)})]},m2.model))})}),$jsx("box",{height:1,flexShrink:0}),$jsxs("box",{flexShrink:0,height:ranksH,flexDirection:wide?"row":"column",gap:wide?2:1,children:[$jsx(Rank,{title:"Tools",rows:tools,fg:theme.success,n:nTools}),$jsx(Rank,{title:"Sources",rows:data2.bySource,fg:theme.info,n:nSrc})]})]})}),$jsx(HintBar,{pairs:[["1/7/3/9","period"],[keys.print("list.refresh"),"reload"]]})]})});var import_react61=__toESM(require_react_production(),1);var SubTabBar=import_react61.memo((props)=>$jsx(TabStrip,{...props}));var TABS=[{name:"Chat",description:"Main chat interface"},{name:"Sessions",description:"Sessions, context, analytics"},{name:"Profiles & Automation",description:"Profiles, cron jobs, kanban boards"},{name:"Config",description:"Config, env, skills, toolsets, memory"},{name:"Eikon",description:"Avatar studio & library"}],TAB_MAX=TABS.length-1,CHAT_TAB=0,SESSIONS_TAB=1,AUTOMATION_TAB=2,CONFIG_TAB=3,EIKON_TAB=4,SUB_TABS={[1]:["List","Context","Analytics"],[2]:["Kanban","Profiles","Cron"],[3]:["Config","Skills","Toolsets","Env","Memory"],[4]:["Library","Catalog","Studio"]},TAB_SLASH={chat:{tab:0,sub:0},sessions:{tab:1,sub:0},context:{tab:1,sub:1},analytics:{tab:1,sub:2},insights:{tab:1,sub:2},kanban:{tab:2,sub:0},automation:{tab:2,sub:0},profiles:{tab:2,sub:1},agents:{tab:2,sub:1},cron:{tab:2,sub:2},config:{tab:3,sub:0},skills:{tab:3,sub:1},toolsets:{tab:3,sub:2},env:{tab:3,sub:3},memory:{tab:3,sub:4},library:{tab:4,sub:0},catalog:{tab:4,sub:1},studio:{tab:4,sub:2}};var SessionsGroup=import_react62.memo((props)=>{let labels=SUB_TABS[SESSIONS_TAB];import_react62.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane,{visible:props.sub===0,children:$jsx(Sessions,{focused:!!props.focused&&props.sub===0,onSwitch:props.onSwitch,onActivateLive:props.onActivateLive,currentId:props.currentId})}),$jsx(Pane,{visible:props.sub===1,children:$jsx(Context,{focused:!!props.focused&&props.sub===1,messages:props.messages,sessionStart:props.sessionStart,info:props.info,usage:props.usage})}),$jsx(Pane,{visible:props.sub===2,children:$jsx(Analytics,{focused:!!props.focused&&props.sub===2})})]})]})}),Pane=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react82=__toESM(require_react_production(),1);var import_react74=__toESM(require_react_production(),1);var acc=new Map;function record(ev,p){let id=p.subagent_id;if(!id)return;let now=Date.now()/1000;if(ev==="start"){acc.set(id,{subagent_id:id,parent_id:p.parent_id??null,depth:p.depth??0,goal:p.goal,model:p.model,started_at:now,tool_count:0,status:"running",trail:[]});return}let r=acc.get(id);if(!r)return;if(ev==="tool"&&p.tool_name){r.tool_count++,r.trail=[...r.trail??[],{name:p.tool_name,preview:p.tool_preview}].slice(-20);return}if(ev==="complete")r.status=p.status??"completed",r.finished_at=now,r.input_tokens=p.input_tokens,r.output_tokens=p.output_tokens,r.cost_usd=p.cost_usd}function trail(id){return acc.get(id)?.trail??[]}function flush(gw,sessionId){if(acc.size===0)return;let subagents=[...acc.values()];acc.clear();let label2=(subagents.filter((s)=>s.parent_id==null).slice(0,2).map((s)=>s.goal).join(" \xB7 ")||`${subagents.length} subagents`).slice(0,120),started=Math.min(...subagents.map((s)=>s.started_at));gw.request("spawn_tree.save",{session_id:sessionId,label:label2,started_at:started,finished_at:Date.now()/1000,subagents}).catch(()=>{})}var import_react65=__toESM(require_react_production(),1);var import_react63=__toESM(require_react_production(),1);var DialogSelect=(props)=>{let filterable=props.filterable??!0,[filter,setFilter]=import_react63.useState(""),[cursor,setCursor]=import_react63.useState(0),mode=import_react63.useRef("kb"),moved=import_react63.useRef(!1),sb=import_react63.useRef(null),theme=useTheme().theme,opts=import_react63.useMemo(()=>props.options.map((o)=>({name:`${props.current==null?"":o.value===props.current?"\u25CF ":" "}${o.title}`,description:o.hint?[o.description,o.hint].filter(Boolean).join(" \u2014 "):o.description??"",value:o.value})),[props.current,props.options]),sel=props.current==null?0:Math.max(0,props.options.findIndex((o)=>o.value===props.current)),desc=props.options.some((o)=>!!o.description||!!o.hint),filtered=import_react63.useMemo(()=>{let lower=filter.toLowerCase();return props.options.filter((o)=>o.title.toLowerCase().includes(lower)||(o.description??"").toLowerCase().includes(lower))},[filter,props.options]),groups=import_react63.useMemo(()=>{let map=new Map;return filtered.forEach((o)=>{let cat=o.category??"",arr=map.get(cat)??[];arr.push(o),map.set(cat,arr)}),map},[filtered]),rowId=(i)=>`ds-row-${i}`,scrollTo=(i)=>sb.current?.scrollChildIntoView(rowId(i));import_react63.useEffect(()=>{if(cursor>=filtered.length)setCursor(Math.max(0,filtered.length-1))},[filtered.length,cursor]),import_react63.useEffect(()=>{if(!props.current){setCursor(0);return}let i=filtered.findIndex((o)=>o.value===props.current),n=Math.max(0,i);setCursor(n),scrollTo(n)},[props.current,filtered]),import_react63.useEffect(()=>{if(!moved.current)return;moved.current=!1;let item=filtered[cursor];if(item&&props.onMove)props.onMove(item)},[cursor,filtered,props.onMove]);let keys=useKeys();useKeyboard((key3)=>{if(!filterable)return;if(handleListKey(keys,key3,{count:filtered.length,setSel:(fn)=>{mode.current="kb",moved.current=!0,setCursor(fn)},scrollTo,page:Math.max(1,(sb.current?.viewport.height??10)-1),onActivate:()=>{let item=filtered[cursor];if(item)props.onSelect(item)}}))return;if(props.onKey?.(key3))return});let idx=0,entries2=Array.from(groups.entries());if(!filterable)return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),$jsx("select",{focused:!0,width:58,height:Math.min(16,Math.max(1,props.options.length*(desc?2:1))),options:opts,selectedIndex:sel,showDescription:desc,showScrollIndicator:props.options.length>8,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,fastScrollStep:Math.max(1,props.options.length),keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"pageup",action:"move-up-fast"},{name:"pagedown",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"}],onChange:(i)=>{let item=props.options[i];if(item&&props.onMove)props.onMove(item)},onSelect:(i)=>{let item=props.options[i];if(item)props.onSelect(item)}}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]});return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.title})}),$jsx("box",{height:1}),filterable?$jsxs($Fragment,{children:[$jsx("input",{value:filter,onInput:(v2)=>{mode.current="kb",setFilter(v2)},placeholder:props.placeholder??"Type to filter...",focused:!0,textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}),$jsx("box",{height:1})]}):null,$jsxs("scrollbox",{ref:sb,scrollY:!0,maxHeight:16,focused:!filterable,contentOptions:{flexDirection:"column"},paddingRight:1,children:[filtered.length===0?$jsx("text",{fg:theme.textMuted,children:"No results found"}):null,entries2.map(([cat,items])=>{let elements=[];if(cat)elements.push($jsx("text",{fg:theme.textMuted,children:$jsx("strong",{children:cat})},`cat-${cat}`));return items.forEach((item)=>{let i=idx++,active=i===cursor,current=item.value===props.current;elements.push($jsxs("box",{id:rowId(i),flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseMove:()=>{mode.current="mouse",moved.current=!0,setCursor((c)=>c===i?c:i)},onMouseOver:()=>{if(mode.current==="mouse")moved.current=!0,setCursor(i)},onMouseDown:()=>props.onSelect(item),paddingLeft:1,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{fg:active?theme.text:theme.textMuted,children:[current?"\u25CF ":" ",item.title,item.description?` \u2014 ${item.description}`:""]})}),item.hint?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:item.hint})}):null]},item.value))}),elements}).flat()]}),props.footer!=null?$jsx("box",{paddingTop:1,children:props.footer}):null]})};var Ctx6=import_react65.createContext(null),CommandProvider=({children:children2})=>{let registry=import_react65.useRef(new Map),enabled2=import_react65.useRef(!0),dialog=useDialog(),keys=useKeys(),all=import_react65.useCallback(()=>{let out=[];return registry.current.forEach((cmds)=>cmds.forEach((c)=>out.push(c))),out},[]),register=import_react65.useCallback((cmds)=>{let id=String(Date.now())+Math.random();return registry.current.set(id,cmds),()=>{registry.current.delete(id)}},[]),setEnabled=import_react65.useCallback((val)=>{enabled2.current=val},[]),open2=import_react65.useCallback(()=>{let cmds=all(),options=cmds.map((c)=>({title:c.title,value:c.value,description:c.description,hint:c.action?keys.print(c.action):void 0,category:c.category}));dialog.replace($jsx(DialogSelect,{title:"Command Palette",options,onSelect:(opt)=>{dialog.clear();let found=cmds.find((c)=>c.value===opt.value);if(found)found.onSelect()},placeholder:"Search commands..."}))},[all,dialog,keys]);useKeyboard((key3)=>{if(!enabled2.current||dialog.open())return;if(keys.match("palette.open",key3))return open2();for(let c of all())if(c.action&&keys.match(c.action,key3))return c.onSelect()});let value=import_react65.useMemo(()=>({register,setEnabled}),[register,setEnabled]);return $jsx(Ctx6.Provider,{value,children:children2})},useCommand=makeUse(Ctx6,"useCommand");var Status=({s})=>{let theme=useTheme().theme,fg2=s==="completed"?theme.success:s==="failed"?theme.error:s==="error"?theme.error:s==="timeout"?theme.error:s==="interrupted"?theme.warning:theme.textMuted;return $jsx("span",{fg:fg2,children:s})},SnapshotView=(props)=>{let theme=useTheme().theme,subs2=props.snap.subagents??[],tok=subs2.reduce((n,s)=>n+(s.input_tokens??0)+(s.output_tokens??0),0),span2=props.snap.started_at&&props.snap.finished_at?dur2(props.snap.finished_at-props.snap.started_at):"\u2014";return $jsxs("box",{flexDirection:"column",width:80,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.entry.label||`${subs2.length} subagents`})}),$jsxs("text",{fg:theme.textMuted,children:[when(props.entry.finished_at)," \xB7 ",span2," \xB7 ",subs2.length," agents \xB7 ",fmt(tok)," tok"]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:20,contentOptions:{flexDirection:"column"},children:subs2.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "+"\xB7 ".repeat(s.depth)}),$jsx("span",{fg:theme.text,children:trunc5(s.goal.replace(/\s+/g," "),60)})]})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["\u2503 "+" ".repeat(2*s.depth+2),$jsx(Status,{s:s.status}),` \xB7 ${s.tool_count}t`,s.finished_at?` \xB7 ${dur2(s.finished_at-s.started_at)}`:"",s.model?` \xB7 ${s.model}`:""]})})]},s.subagent_id))})]})};function openSpawnHistory(dialog,gw,sessionId){gw.request("spawn_tree.list",{session_id:sessionId,limit:50}).then((r)=>{let entries2=r.entries??[];dialog.replace($jsx(DialogSelect,{title:"Spawn history",placeholder:entries2.length?"filter\u2026":"no saved spawn trees",options:entries2.map((e)=>({value:e.path,title:`${e.count.toString().padStart(2)}\xD7 ${trunc5(e.label||"(unlabeled)",40)}`,description:when(e.finished_at),category:e.session_id===sessionId?"This session":e.session_id})),onSelect:(opt)=>{let entry2=entries2.find((e)=>e.path===opt.value);gw.request("spawn_tree.load",{path:entry2.path}).then((snap)=>dialog.replace($jsx(SnapshotView,{entry:entry2,snap}))).catch(()=>dialog.clear())}}))}).catch(()=>dialog.clear())}var import_react68=__toESM(require_react_production(),1);var Dialog=(props)=>{let theme=useTheme().theme,keys=useKeys();useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.accept",key3))return props.onClose()});let d2=props.d,req=d2.env_requires.filter((e)=>e.required),opt=d2.env_requires.filter((e)=>!e.required),link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs("box",{flexDirection:"column",minWidth:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Distribution \xB7 ${props.profile}`})})}),$jsxs("box",{flexDirection:"column",children:[$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0],["Author",d2.author||void 0],["License",d2.license||void 0],["Description",d2.description||void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed",Number.isFinite(when2)?ago(when2/1000):void 0],["Owned",d2.distribution_owned.length?d2.distribution_owned.join(", "):void 0]]})]}),d2.env_requires.length?$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Environment variables"})})}),req.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Required"})}),req.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null,opt.length?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Optional"})}),opt.map((e)=>$jsx(EnvRow,{name:e.name,desc:e.description,fallback:e.default},e.name))]}):null]}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:`[${keys.print("dialog.cancel")}] close`})})]})},EnvRow=(props)=>{let theme=useTheme().theme,tail=[props.desc,props.fallback?`default: ${props.fallback}`:""].filter(Boolean).join(" \xB7 ");return $jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:" "})}),$jsx("box",{width:22,flexShrink:0,children:$jsx("text",{fg:theme.accent,children:props.name})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tail})})]})};function openDistributionInfo(dialog,opts){dialog.replace($jsx(Dialog,{profile:opts.profile,d:opts.d,yaml:opts.yaml,onClose:()=>dialog.clear()}))}function openProfileMenu(dialog,p,ops){let opts=[...ops.switch&&!p.is_active?[{category:"Switch",value:"switch",title:`Switch to '${p.name}'`,description:"restart gateway under this HERMES_HOME \u2014 ends current session"}]:[],{category:"Open",value:"soul",title:"SOUL.md",description:"edit persona/system prompt"},{category:"Open",value:"config",title:"config.yaml",description:"model, provider, toolsets"},...p.has_env?[{category:"Open",value:"env",title:".env",description:"API keys + secrets"}]:[],{category:"Open",value:"dir",title:"Directory",description:p.path},...p.distribution?[{category:"Distribution",value:"dist-info",title:"Info",description:`v${p.distribution.version}${p.distribution.source?` \xB7 ${p.distribution.source}`:""}`},{category:"Distribution",value:"dist-update",title:"Update",description:`hermes profile update ${p.name}${p.is_active?" \xB7 ends current session":""}`}]:[],...p.is_sticky?[{category:"Default",value:"unsticky",title:"Clear sticky default",description:"hermes profile use --clear"}]:[{category:"Default",value:"sticky",title:"Set as sticky default",description:`hermes profile use ${p.name}`}],{category:"Manage",value:"export",title:"Export",description:`hermes profile export ${p.name}`},...p.is_default||p.is_active?[]:[{category:"Manage",value:"delete",title:"Delete",description:"irreversible \u2014 removes config, env, memory, sessions"}]];dialog.replace($jsx(DialogSelect,{title:`Profile \xB7 ${p.name}${p.is_active?" (active)":""}`,options:opts,onSelect:(o)=>{if(o.value==="dist-info"){if(!p.distribution)return dialog.clear();return openDistributionInfo(dialog,{profile:p.name,d:p.distribution,yaml:p.sources.distribution})}if(o.value==="dist-update"){if(!p.distribution)return dialog.clear();return openUpdateDistribution(dialog,p,(force)=>ops.update(p,force))}if(dialog.clear(),o.value==="switch")return ops.switch?.();if(o.value==="soul")return openFile(p.sources.soul.file);if(o.value==="config")return openFile(p.sources.config.file);if(o.value==="env")return openFile(p.sources.env.file);if(o.value==="dir")return openFile(p.path);if(o.value==="sticky")return ops.sticky(p);if(o.value==="unsticky")return ops.unsticky();if(o.value==="export")return ops.export(p);if(o.value==="delete")return ops.remove(p)}}))}var UpdateForm=(props)=>{let theme=useTheme().theme,keys=useKeys(),[force,setForce]=import_react68.useState(!1);useKeyboard((key3)=>{if(keys.match("dialog.cancel",key3)||keys.match("dialog.deny",key3))return props.done(null);if(keys.match("dialog.confirm",key3)||keys.match("dialog.accept",key3))return props.done(force);if(key3.name==="space"||key3.name===" ")return setForce((f)=>!f)});let d2=props.p.distribution;return $jsxs("box",{flexDirection:"column",width:62,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Update distribution?"})})}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:`'${props.p.name}' \xB7 v${d2.version}${d2.source?` \xB7 ${d2.source}`:""}`})}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:"Re-pulls from source; distribution-owned files are overwritten."})}),props.p.is_active?$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.warning,children:"\u26A0 This is the active profile. The gateway will re-spawn "+"and the current session will end."})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:force?theme.warning:theme.textMuted,children:`${force?"[x]":"[ ]"} --force-config \xB7 also overwrite config.yaml`})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`[${keys.print("dialog.confirm")}] update [Space] toggle force [${keys.print("dialog.cancel")}] cancel`})})]})};function openUpdateDistribution(dialog,p,onConfirm){dialog.replace($jsx(UpdateForm,{p,done:(force)=>{if(dialog.clear(),force!==null)onConfirm(force)}}))}var import_react70=__toESM(require_react_production(),1);import{existsSync as existsSync14,readFileSync as readFileSync7}from"fs";import{readdir as readdir3}from"fs/promises";import{homedir as homedir6}from"os";import{join as join11,basename as basename10,dirname as dirname9}from"path";import{Database as Database2}from"bun:sqlite";var home3=()=>process.env.HOME||homedir6(),hermesHome=()=>process.env.HERMES_HOME||join11(home3(),".hermes");function root(){let hh=hermesHome(),parent2=dirname9(hh);return basename10(parent2)==="profiles"?dirname9(parent2):hh}function profileNameFrom(hh){let parent2=dirname9(hh);return basename10(parent2)==="profiles"?basename10(hh):"default"}function activeProfileName(){return profileNameFrom(hermesHome())}function stickyDefault(){try{return readFileSync7(join11(root(),"active_profile"),"utf-8").trim()||null}catch{return null}}var ID_RE=/^[a-z0-9][a-z0-9_-]{0,63}$/;function readModel(dir){try{let raw=readFileSync7(join11(dir,"config.yaml"),"utf-8"),block=raw.split(/^model:\s*$/m)[1]?.split(/^\S/m)[0]??"",m2=block.match(/^\s+(?:default|model):\s*(.+)$/m)?.[1]?.trim()??raw.match(/^model:\s*(\S.+)$/m)?.[1]?.trim(),p=block.match(/^\s+provider:\s*(.+)$/m)?.[1]?.trim(),clean3=(s)=>s?.replace(/^["']|["']$/g,"")??null;return[clean3(m2),clean3(p)]}catch{return[null,null]}}async function countSkills(dir){let glob=new Bun.Glob("**/SKILL.md"),n=0;try{for await(let _2 of glob.scan({cwd:join11(dir,"skills"),onlyFiles:!0}))n++}catch{}return n}function gatewayRunning(dir){try{let raw=readFileSync7(join11(dir,"gateway.pid"),"utf-8").trim(),pid2=raw.startsWith("{")?Number(JSON.parse(raw).pid):Number(raw);if(!Number.isFinite(pid2)||pid2<=0)return!1;return process.kill(pid2,0),!0}catch{return!1}}function soul(dir){try{return readFileSync7(join11(dir,"SOUL.md"),"utf-8").replace(/^#[^\n]*\n+/,"").replace(/^\s+/,"").slice(0,400)}catch{return""}}function readDistributionManifest(dir){let path7=join11(dir,"distribution.yaml");if(!existsSync14(path7))return null;let data2=(()=>{try{return $parse(readFileSync7(path7,"utf-8"))}catch{return null}})();if(!data2||typeof data2!=="object"||Array.isArray(data2))return null;let d2=data2,name=typeof d2.name==="string"?d2.name.trim():"";if(!name)return null;let envs=(Array.isArray(d2.env_requires)?d2.env_requires:[]).flatMap((e)=>{if(!e||typeof e!=="object")return[];let r=e,n=typeof r.name==="string"?r.name.trim():"";if(!n)return[];return[{name:n,description:typeof r.description==="string"?r.description:"",required:r.required===void 0?!0:Boolean(r.required),default:typeof r.default==="string"?r.default:null}]}),owned=(Array.isArray(d2.distribution_owned)?d2.distribution_owned:[]).map((p)=>typeof p==="string"?p.trim().replace(/\/+$/,""):"").filter((p)=>p.length>0);return{name,version:typeof d2.version==="string"?d2.version:"0.1.0",description:typeof d2.description==="string"?d2.description:"",hermes_requires:typeof d2.hermes_requires==="string"?d2.hermes_requires:"",author:typeof d2.author==="string"?d2.author:"",license:typeof d2.license==="string"?d2.license:"",env_requires:envs,distribution_owned:owned,source:typeof d2.source==="string"?d2.source:"",installed_at:typeof d2.installed_at==="string"?d2.installed_at:""}}var src2=(file,label2)=>({file,relative:file.replace(home3()+"/","~/"),label:label2});async function info(name,dir,active,sticky){let[model,provider]=readModel(dir),alias=join11(home3(),".local","bin",name);return{name,path:dir,is_default:name==="default",is_active:name===active,is_sticky:name===sticky,gateway_running:gatewayRunning(dir),model,provider,has_env:existsSync14(join11(dir,".env")),skill_count:await countSkills(dir),has_alias:name!=="default"&&existsSync14(alias),soul_preview:soul(dir),distribution:readDistributionManifest(dir),sources:{dir:src2(dir,dir.replace(home3()+"/","~/")),config:src2(join11(dir,"config.yaml"),"config.yaml"),soul:src2(join11(dir,"SOUL.md"),"SOUL.md"),env:src2(join11(dir,".env"),".env"),distribution:src2(join11(dir,"distribution.yaml"),"distribution.yaml")}}}async function listProfiles(activeHome){let r=root(),active=profileNameFrom(activeHome??hermesHome()),sticky=stickyDefault(),jobs=[];if(existsSync14(r))jobs.push(info("default",r,active,sticky));let pr=join11(r,"profiles");if(existsSync14(pr))for(let e of await readdir3(pr,{withFileTypes:!0})){if(!e.isDirectory()||!ID_RE.test(e.name))continue;jobs.push(info(e.name,join11(pr,e.name),active,sticky))}return Promise.all(jobs)}function validateName(name,existing){if(!ID_RE.test(name))return"must match [a-z0-9][a-z0-9_-]{0,63}";if(existing.includes(name))return"already exists";if(["hermes","default","test","tmp","root","sudo"].includes(name))return"reserved name";return null}function readPrefs(dir){try{let raw=JSON.parse(readFileSync7(join11(dir,"herm","tui.json"),"utf-8"));return{theme:raw.theme,eikon:raw.eikon??(raw.eikonPath?basename10(raw.eikonPath,".eikon"):void 0),keys:raw.keys?Object.keys(raw.keys).length:0}}catch{return null}}async function profileStats(dir){let sessions=null,messages=null,dbPath=join11(dir,"state.db");if(existsSync14(dbPath))try{let db=new Database2(dbPath,{readwrite:!0,create:!1}),r=db.query("SELECT COUNT(*) AS s FROM sessions WHERE message_count > 0").get(),m2=db.query("SELECT COALESCE(SUM(message_count), 0) AS m FROM sessions").get();sessions=r.s,messages=m2.m,db.close()}catch{}let crons=null;try{let jobs=await Bun.file(join11(dir,"cron","jobs.json")).json();crons=Array.isArray(jobs)?jobs.length:jobs&&typeof jobs==="object"&&Array.isArray(jobs.jobs)?jobs.jobs.length:0}catch{crons=existsSync14(join11(dir,"cron"))?0:null}return{sessions,messages,crons,prefs:readPrefs(dir)}}var ORDER2=["name","clone","alias"];function openCreateProfile(dialog,opts){return new Promise((resolve4)=>{let done=(r)=>{dialog.clear(),resolve4(r)};dialog.replace($jsx(Form,{existing:opts.existing,done}))})}var Form=({existing,done})=>{let theme=useTheme().theme,[name,setName]=import_react70.useState(""),[cloneIdx,setCloneIdx]=import_react70.useState(0),[alias,setAlias]=import_react70.useState(!0),[field,setField]=import_react70.useState("name"),options=["(fresh)",...existing],err=name?validateName(name,existing):null,valid=!!name&&!err,submit2=()=>{if(!valid)return;done({name,cloneFrom:cloneIdx===0?null:options[cloneIdx],alias})},moveField=(dir)=>{let i=ORDER2.indexOf(field);setField(ORDER2[(i+dir+ORDER2.length)%ORDER2.length])};useKeyboard((key3)=>{if(key3.name==="escape")return done(null);if(key3.name==="tab")return moveField(key3.shift?-1:1);if(key3.name==="return")return submit2();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[a-z0-9_-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(field==="clone"){if(key3.name==="up")return setCloneIdx((i)=>Math.max(0,i-1));if(key3.name==="down")return setCloneIdx((i)=>Math.min(options.length-1,i+1));return}if(field==="alias"){if(key3.name==="space"||key3.name===" ")return setAlias((a)=>!a)}});let focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New Profile"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:valid||!name?theme.text:theme.error,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:" a-z 0-9 _ - \xB7 lowercase"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsx("text",{fg:theme.textMuted,children:"Clone from (\u2191\u2193)"})}),options.map((o,i)=>$jsx("box",{height:1,backgroundColor:focusBg("clone"),children:$jsxs("text",{fg:i===cloneIdx?theme.accent:theme.text,children:[i===cloneIdx?"\u25B8 ":" ",o]})},o)),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] shell alias":"[ ] shell alias"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:valid?"Enter create \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel":err??"type a name"})})]})};var import_react72=__toESM(require_react_production(),1);import{rmSync as rmSync2,mkdtempSync as mkdtempSync2}from"fs";import{join as join12}from"path";import{tmpdir as tmpdir2}from"os";var shq=(s)=>`'${s.replace(/'/g,"'\\''")}'`;function openInstallDistribution(dialog,gw){return new Promise((resolve4)=>{askSource(dialog,gw,(r)=>{dialog.clear(),resolve4(r)})})}function askSource(dialog,gw,done){dialog.replace($jsx(Step1,{onSubmit:(source)=>preview(dialog,gw,source,done),onCancel:()=>done(null)}))}async function preview(dialog,gw,source,done){let tmp=mkdtempSync2(join12(tmpdir2(),"herm-dist-preview-")),cleanup=()=>{try{rmSync2(tmp,{recursive:!0,force:!0})}catch{}},state2={cancelled:!1},cancel=()=>{state2.cancelled=!0,cleanup(),done(null)};dialog.replace($jsx(Loading,{label:`Cloning ${source}\u2026`,onCancel:cancel}),void 0,{ownCancel:!0});let cmd=`git clone --depth 1 --quiet ${shq(source)} ${shq(tmp)} 2>&1`,r=await gw.request("shell.exec",{command:cmd}).catch((e)=>({stdout:"",stderr:e.message,code:-1}));if(state2.cancelled)return;if(r.code!==0){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Clone failed",body:(r.stderr||r.stdout||`exit ${r.code}`).trim(),onClose:()=>done(null)}));return}let manifest2=readDistributionManifest(tmp);if(!manifest2){cleanup(),dialog.replace($jsx(ErrorBox,{title:"Not a distribution",body:`No valid distribution.yaml at the root of ${source}. A manifest must declare at minimum a 'name:' key.`,onClose:()=>done(null)}));return}dialog.replace($jsx(ConfirmStep,{source,manifest:manifest2,onConfirm:(r2)=>{cleanup(),done(r2)},onCancel:()=>{cleanup(),done(null)}}),void 0,{ownCancel:!0})}var Step1=(p)=>{let theme=useTheme().theme,[value,setValue]=import_react72.useState("");return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:64,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Source \u2014 git URL, github.com/owner/repo, or local directory"})}),$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)p.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?"Enter preview \xB7 Esc cancel":"Esc cancel"})})]})},Loading=(p)=>{let theme=useTheme().theme;return useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel()}),$jsxs("box",{flexDirection:"column",width:54,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:p.label})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to cancel"})})]})},ErrorBox=(p)=>{let theme=useTheme().theme,keys=useKeys();return useKeyboard((key3)=>{if(keys.match("dialog.accept",key3)||keys.match("dialog.cancel",key3))return p.onClose()}),$jsxs("box",{flexDirection:"column",width:68,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter / Esc to close"})})]})},ORDER3=["name","alias"],ConfirmStep=(p)=>{let theme=useTheme().theme,keys=useKeys(),[name,setName]=import_react72.useState(""),[alias,setAlias]=import_react72.useState(!1),[field,setField]=import_react72.useState("name"),fire=()=>p.onConfirm({source:p.source,manifest:p.manifest,name:name.trim()||null,alias}),move=(dir)=>{let i=ORDER3.indexOf(field);setField(ORDER3[(i+dir+ORDER3.length)%ORDER3.length])};useKeyboard((key3)=>{if(key3.name==="escape")return p.onCancel();if(key3.name==="tab")return move(key3.shift?-1:1);if(field!=="name"&&keys.match("dialog.accept",key3))return fire();if(field==="alias"&&(key3.name==="space"||key3.name===" "))return setAlias((a)=>!a)});let m2=p.manifest,reqEnv=m2.env_requires.filter((e)=>e.required),optEnv=m2.env_requires.filter((e)=>!e.required),focusBg=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Install Distribution"})})}),$jsx("box",{height:1}),$jsx(KV2,{label:"Name",value:`${m2.name}${m2.version?` v${m2.version}`:""}`,theme}),m2.description?$jsx(KV2,{label:"About",value:m2.description,theme,wrap:!0}):null,m2.author?$jsx(KV2,{label:"Author",value:m2.author,theme}):null,m2.license?$jsx(KV2,{label:"License",value:m2.license,theme}):null,m2.hermes_requires?$jsx(KV2,{label:"Requires",value:`hermes ${m2.hermes_requires}`,theme}):null,$jsx(KV2,{label:"Source",value:p.source,theme}),m2.distribution_owned.length>0?$jsx(KV2,{label:"Owns",value:m2.distribution_owned.join(", "),theme,wrap:!0}):null,m2.env_requires.length>0?$jsx(KV2,{label:"Env",value:envSummary(reqEnv,optEnv),theme}):null,$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("name"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Name as"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:field==="name"?$jsx("input",{value:name,onInput:setName,onSubmit:fire,focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement}):$jsx("text",{fg:name?theme.text:theme.textMuted,children:name||`(${m2.name})`})})]}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:focusBg("alias"),children:[$jsx("box",{width:11,children:$jsx("text",{fg:theme.textMuted,children:"Alias"})}),$jsx("text",{fg:alias?theme.accent:theme.textMuted,children:alias?"[x] create shell wrapper":"[ ] create shell wrapper"})]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter install \xB7 Tab next field \xB7 Space toggle \xB7 Esc cancel"})})]})},KV2=(p)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:11,flexShrink:0,children:$jsx("text",{fg:p.theme.textMuted,children:p.label})}),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("text",{fg:p.theme.text,wrapMode:p.wrap?"word":"none",children:p.value})})]});function envSummary(req,opt){return[req.length>0?`${req.length} required (${req.map((e)=>e.name).join(", ")})`:"",opt.length>0?`${opt.length} optional`:""].filter(Boolean).join(" \xB7 ")}var running=(s)=>!s||s==="running"||s==="queued";function tree(recs,live,now){let ids=new Set(recs.map((r)=>r.subagent_id)),by=new Map;for(let r of recs){let k2=r.parent_id&&ids.has(r.parent_id)?r.parent_id:"";(by.get(k2)??by.set(k2,[]).get(k2)).push(r)}let build2=(r)=>{let kids=(by.get(r.subagent_id)??[]).map(build2),lv=live.get(r.subagent_id)??{},dur3=r.started_at!=null?Math.max(0,now-r.started_at):0,a={agents:1,tools:lv.tool_count??r.tool_count??0,dur:dur3,tok:(lv.input_tokens??0)+(lv.output_tokens??0),cost:lv.cost_usd??0,active:running(lv.status??r.status)?1:0,depth:0,hot:0};for(let k2 of kids)a={agents:a.agents+k2.agg.agents,tools:a.tools+k2.agg.tools,dur:a.dur+k2.agg.dur,tok:a.tok+k2.agg.tok,cost:a.cost+k2.agg.cost,active:a.active+k2.agg.active,depth:Math.max(a.depth,k2.agg.depth+1),hot:0};return a.hot=a.dur>0?a.tools/a.dur:0,{rec:r,agg:a,kids}};return(by.get("")??[]).map(build2)}function totals(nodes){let z2={agents:0,tools:0,dur:0,tok:0,cost:0,active:0,depth:0,hot:0};for(let n of nodes)z2.agents+=n.agg.agents,z2.tools+=n.agg.tools,z2.dur+=n.agg.dur,z2.tok+=n.agg.tok,z2.cost+=n.agg.cost,z2.active+=n.agg.active,z2.depth=Math.max(z2.depth,n.agg.depth+1);return z2.hot=z2.dur>0?z2.tools/z2.dur:0,z2}var SPARK=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];function spark(nodes){let w2=[],walk=(ns,d2)=>{if(ns.length===0)return;w2[d2]=(w2[d2]??0)+ns.length;for(let n of ns)walk(n.kids,d2+1)};if(walk(nodes,0),w2.length===0)return"";let max=Math.max(...w2);return w2.map((v2)=>v2<=0?" ":SPARK[Math.min(7,Math.ceil(v2/max*7))]).join("")}var tk=(n)=>n<1000?String(Math.round(n)):n<1e4?`${(n/1000).toFixed(1)}k`:`${Math.round(n/1000)}k`,$$=(n)=>n<=0?"":n<0.01?"<$0.01":n<10?`$${n.toFixed(2)}`:`$${n.toFixed(1)}`,sec=(s)=>{if(s<60)return`${Math.round(s)}s`;let m2=Math.floor(s/60),r=Math.round(s-m2*60);return r===0?`${m2}m`:`${m2}m${r}s`};function summary(a){let p=[`d${a.depth}`,`${a.agents} agent${a.agents===1?"":"s"}`];if(a.tools>0)p.push(`${a.tools} tools`);if(a.dur>0)p.push(sec(a.dur));if(a.tok>0)p.push(`${tk(a.tok)} tok`);if(a.cost>0)p.push($$(a.cost));if(a.active>0)p.push(`\u26A1${a.active}`);return p.join(" \xB7 ")}function heat(hot,peak,buckets){if(hot<=0||peak<=0||buckets<=1)return 0;return Math.min(buckets-1,Math.round(Math.min(1,hot/peak)*(buckets-1)))}function peak(nodes){let p=0,walk=(ns)=>{for(let n of ns)p=Math.max(p,n.agg.hot),walk(n.kids)};return walk(nodes),p}var ProfileRow=import_react74.memo((props)=>{let theme=useTheme().theme,{p,idx:i}=props,[x2,setX]=import_react74.useState(!1);return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),onMouseDown:()=>props.onEnter(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:p.is_active?theme.accent:theme.text,children:p.is_active?$jsx("strong",{children:p.name}):p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605"}):null,p.distribution?$jsx("span",{fg:theme.info,children:" \u2B22"}):null,p.gateway_running?$jsx("span",{fg:theme.success,children:" \u25CF"}):null]})}),$jsx("box",{width:4,height:1,children:$jsx("text",{fg:theme.textMuted,children:p.is_active?" you":""})}),p.is_default||p.is_active?$jsx("box",{width:3}):$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onDelete(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})}),DistBlock=import_react74.memo((props)=>{let theme=useTheme().theme,d2=props.d,req=d2.env_requires.filter((e)=>e.required).length,opt=d2.env_requires.length-req,link2=d2.source?{file:d2.source,relative:d2.source,label:d2.source}:props.yaml,when2=d2.installed_at?Date.parse(d2.installed_at):NaN;return $jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:"Distribution"})})}),$jsx(KVBlock,{rows:[["Name",d2.name],["Version",`v${d2.version}`],["Requires",d2.hermes_requires?`Hermes ${d2.hermes_requires}`:void 0]]}),$jsx(KVLink,{label:"Source",source:link2,text:d2.source||props.yaml.label}),$jsx(KVBlock,{rows:[["Installed at",Number.isFinite(when2)?ago(when2/1000):void 0],["Env vars",d2.env_requires.length?`${req} required, ${opt} optional`:void 0]]})]})}),ProfileDetail=import_react74.memo((props)=>{let{theme,syntaxStyle}=useTheme(),p=props.p,s=props.stats;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{height:1,children:$jsxs("text",{fg:theme.accent,children:[$jsx("strong",{children:p.name}),p.is_sticky?$jsx("span",{fg:theme.warning,children:" \u2605 sticky default"}):null]})}),$jsx("box",{height:1}),$jsx(KVLink,{label:"Path",source:p.sources.dir,text:p.sources.dir.relative}),$jsx(KV,{label:"Active",value:p.is_active?"yes (this session)":"no",fg:p.is_active?theme.accent:theme.textMuted}),$jsx(KV,{label:"Model",value:p.model??"\u2014"}),$jsx(KV,{label:"Provider",value:p.provider??"\u2014"}),$jsx(KV,{label:"Skills",value:String(p.skill_count)}),$jsx(KV,{label:"Sessions",value:s?s.sessions==null?"\u2014":`${fmt(s.sessions)} (${fmt(s.messages??0)} msgs)`:"\u2026"}),$jsx(KV,{label:"Cron jobs",value:s?s.crons==null?"\u2014":String(s.crons):"\u2026"}),$jsx(KV,{label:"Theme",value:s?s.prefs?.theme??"\u2014":"\u2026"}),$jsx(KV,{label:"Avatar",value:s?s.prefs?.eikon??"\u2014":"\u2026"}),s?.prefs?.keys?$jsx(KV,{label:"Keybinds",value:`${s.prefs.keys} overrides`}):null,$jsx(KV,{label:"Gateway",value:p.gateway_running?"running":"stopped",fg:p.gateway_running?theme.success:theme.textMuted}),p.has_alias?$jsx(KV,{label:"Alias",value:`${p.name} (shell)`}):null,p.distribution?$jsx(DistBlock,{d:p.distribution,yaml:p.sources.distribution}):null,$jsx("box",{height:1}),$jsx(KVLink,{label:"Config",source:p.sources.config}),$jsx(KVLink,{label:"Soul",source:p.sources.soul}),p.has_env?$jsx(KVLink,{label:"Env",source:p.sources.env}):$jsx(KV,{label:"Env",value:"\u2014"}),p.soul_preview?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"SOUL.md"})}),$jsx("markdown",{content:p.soul_preview,fg:theme.markdownText,syntaxStyle})]}):null]})})}),HOT=["\u2800","\u2801","\u2803","\u2807","\u280F","\u281F","\u283F","\u287F","\u28FF"],DelegRow=import_react74.memo((props)=>{let theme=useTheme().theme,{r,idx:i,now}=props,[x2,setX]=import_react74.useState(!1),up=r.started_at?dur2(now-r.started_at):"\u2014",hotFg=[theme.textMuted,theme.textMuted,theme.text,theme.info,theme.info,theme.accent,theme.accent,theme.warning,theme.error][props.hot]??theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:props.selected?theme.backgroundElement:void 0,onMouseOver:()=>props.onHover(i),children:[$jsx("box",{width:2,children:$jsx("text",{fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "})}),$jsx("box",{width:2,children:$jsxs("text",{fg:hotFg,children:[HOT[props.hot]," "]})}),$jsx("box",{flexGrow:1,minWidth:8,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\xB7 ".repeat(r.depth)}),$jsx("span",{fg:theme.text,children:r.goal.replace(/\s+/g," ")})]})}),$jsx("box",{width:14,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:trunc5(r.model??"",13)})}),$jsx("box",{width:5,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:String(r.tool_count??0)})}),$jsx("box",{width:8,height:1,flexDirection:"row",justifyContent:"flex-end",children:$jsx("text",{fg:theme.textMuted,children:up})}),$jsx("box",{width:3,onMouseDown:(e)=>{e.stopPropagation(),props.onKill(i)},onMouseOver:()=>setX(!0),onMouseOut:()=>setX(!1),children:$jsx("text",{fg:x2?theme.error:theme.textMuted,children:" \u2715"})})]})});function preorder(recs){let byParent=new Map;for(let r of recs){let k2=r.parent_id??null;(byParent.get(k2)??byParent.set(k2,[]).get(k2)).push(r)}let out=[],seen=new Set,walk=(k2)=>{for(let r of byParent.get(k2)??[]){if(seen.has(r.subagent_id))continue;seen.add(r.subagent_id),out.push(r),walk(r.subagent_id)}};walk(null);for(let r of recs)if(!seen.has(r.subagent_id))out.push(r);return out}var DelegDetail=import_react74.memo((props)=>{let theme=useTheme().theme,{r,live,agg,now}=props,tc=live?.tool_count??r.tool_count??0,tr=trail(r.subagent_id);return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",width:"100%",children:[$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.accent,wrapMode:"word",children:$jsx("strong",{children:r.goal})})}),agg&&agg.agents>1?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:summary(agg)})}):null,$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",live?.status??r.status??"running"],["Model",r.model??"\u2014"],["Depth",String(r.depth)],["Parent",r.parent_id??"(root)"],["Uptime",r.started_at?dur2(now-r.started_at):"\u2014"],["Tools",String(tc)],["Tokens",live?`${fmt(live.input_tokens??0)} in / ${fmt(live.output_tokens??0)} out`:void 0],["Cost",live?.cost_usd!=null?`$${live.cost_usd.toFixed(4)}`:void 0]]}),live?.thinking?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"thinking"})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:trunc5(live.thinking,200)})})]}):null,tr.length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"recent tools"})}),tr.slice(-8).map((t2,i)=>$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:t2.name.padEnd(14)}),$jsx("span",{fg:theme.textMuted,children:t2.preview?trunc5(t2.preview.replace(/\s+/g," "),40):""})]})},i))]}):null]})})}),Agents=import_react74.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),[pane,setPane]=import_react74.useState("profiles"),[pView,setPView]=import_react74.useState("list"),[profiles,setProfiles]=import_react74.useState([]),[deleg,setDeleg]=import_react74.useState(null),[liveMap,setLiveMap]=import_react74.useState(()=>new Map),[now,setNow]=import_react74.useState(()=>Date.now()/1000),[pSel,setPSel]=import_react74.useState(0),[dSel,setDSel]=import_react74.useState(0),[err,setErr]=import_react74.useState(""),active=preorder(deleg?.active??[]),nodes=tree(deleg?.active??[],liveMap,now),all=totals(nodes),hotPeak=peak(nodes),aggOf=new Map;{let walk=(ns)=>{for(let n of ns)aggOf.set(n.rec.subagent_id,n.agg),walk(n.kids)};walk(nodes)}let live=import_react74.useRef({profiles,active});live.current={profiles,active};let gwHome=import_react74.useRef(void 0),[stats,setStats]=import_react74.useState(()=>new Map),[sticky,setSticky]=import_react74.useState(stickyDefault),loadProfiles=import_react74.useCallback(()=>{setStats(new Map),setSticky(stickyDefault()),listProfiles(gwHome.current).then((ps)=>{setProfiles(ps),setErr("")}).catch((e)=>setErr(`profiles: ${e.message}`))},[]);import_react74.useEffect(()=>{gw.request("config.get",{key:"profile"}).then((r)=>{gwHome.current=r.home}).catch(()=>{}).finally(loadProfiles)},[gw,loadProfiles]);let loadDeleg=import_react74.useCallback(()=>{gw.request("delegation.status").then((r)=>{setDeleg(r),setNow(Date.now()/1000)}).catch(()=>setDeleg({active:[],paused:!1,max_spawn_depth:0,max_concurrent_children:0}))},[gw]);import_react74.useEffect(loadDeleg,[loadDeleg]),import_react74.useEffect(()=>{if(!props.focused)return;let ms2=(deleg?.active.length??0)>0?1500:5000,t2=setInterval(loadDeleg,ms2);return()=>clearInterval(t2)},[props.focused,deleg?.active.length,loadDeleg]),useGatewayEvent((ev)=>{if(!ev.type.startsWith("subagent."))return;let p=ev.payload,id=p.subagent_id;if(!id)return;if(setLiveMap((prev)=>{let next=new Map(prev),cur=next.get(id)??{tool_count:0};switch(ev.type){case"subagent.start":next.set(id,{tool_count:0});break;case"subagent.tool":next.set(id,{...cur,tool_count:cur.tool_count+1,last_tool:p.tool_name,last_preview:p.tool_preview});break;case"subagent.thinking":next.set(id,{...cur,thinking:p.text});break;case"subagent.complete":next.set(id,{...cur,status:p.status,input_tokens:p.input_tokens,output_tokens:p.output_tokens,cost_usd:p.cost_usd});break}return next}),ev.type==="subagent.start"||ev.type==="subagent.complete")loadDeleg()});let sh=import_react74.useCallback((cmd2)=>gw.request("shell.exec",{command:cmd2}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||"exit "+r.code).trim());return r.stdout}),[gw]),pHover=import_react74.useCallback((i)=>setPSel(i),[]),dHover=import_react74.useCallback((i)=>setDSel(i),[]),pDelete=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_default||p.is_active)return;let warn=p.gateway_running?`
|
|
4125
4124
|
|
|
4126
4125
|
Its gateway is running and will be stopped first (may take up to ~10s).`:"";if(!await openConfirm(dialog,{title:"Delete Profile?",body:`'${p.name}' \u2014 config, env, memory, skills, and sessions will be removed. This cannot be undone.${warn}`,yes:"delete",danger:!0}))return;sh(`hermes profile delete ${p.name} -y`).then(()=>{toast.show({variant:"success",message:`Deleted '${p.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,dialog,toast,loadProfiles]),pSwitch=import_react74.useCallback(async(i)=>{let p=live.current.profiles[i];if(!p||p.is_active||!props.onSwitchProfile)return;if(await openConfirm(dialog,{title:`Switch to '${p.name}'?`,body:"The gateway restarts under this profile's HERMES_HOME. The current session ends (it stays in the outgoing profile's history).",yes:"switch"}))props.onSwitchProfile(p.path,p.name)},[dialog,props.onSwitchProfile]),pUpdate=import_react74.useCallback((p,force)=>{let cmd2=`hermes profile update ${p.name} -y${force?" --force-config":""}`;toast.show({variant:"info",message:`Updating '${p.name}'\u2026`}),sh(cmd2).then(()=>{if(toast.show({variant:"success",message:`Updated '${p.name}'`}),p.is_active&&props.onSwitchProfile){props.onSwitchProfile(p.path,p.name);return}loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message}))},[sh,toast,loadProfiles,props.onSwitchProfile]),pEnter=import_react74.useCallback((i)=>{setPSel(i);let p=live.current.profiles[i];if(!p)return;openProfileMenu(dialog,p,{switch:props.onSwitchProfile?()=>pSwitch(i):void 0,sticky:(pp)=>sh(`hermes profile use ${pp.name}`).then(()=>{toast.show({variant:"success",message:`Sticky default \u2192 '${pp.name}'`}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),unsticky:()=>sh("hermes profile use --clear").then(()=>{toast.show({variant:"info",message:"Cleared sticky default"}),loadProfiles()}).catch((e)=>toast.show({variant:"error",message:e.message})),export:(pp)=>sh(`hermes profile export ${pp.name}`).then((out)=>toast.show({variant:"success",message:trunc5(out.trim()||`Exported '${pp.name}'`,80)})).catch((e)=>toast.show({variant:"error",message:e.message})),remove:()=>pDelete(i),update:(pp,force)=>pUpdate(pp,force)})},[sh,dialog,toast,loadProfiles,pDelete,pSwitch,pUpdate,props.onSwitchProfile]),dKill=import_react74.useCallback(async(i)=>{let r=live.current.active[i];if(!r)return;if(!await openConfirm(dialog,{title:"Interrupt subagent?",body:`${trunc5(r.goal,120)}
|
|
4127
4126
|
|
|
@@ -4145,23 +4144,26 @@ Moves to 'archived' and ends any open run. Children stay; their dependency on th
|
|
|
4145
4144
|
|
|
4146
4145
|
Reset these slots to auto so they follow the main model?`,yes:"reset stale",no:"keep"})){toast.show({variant:"warning",message:`Aux still pinned to another provider: ${names}. Press X to reset all to auto.`});return}for(let slot of stale){let r=await resetAux(gw,slot.key);if(r.failed.length){toast.show({variant:"error",message:`${slot.label}: ${r.failed.map((f)=>f.err).join("; ")}`});return}}toast.show({variant:"success",message:`Reset ${stale.length} aux slot${stale.length===1?"":"s"} \u2192 auto`}),load4()};openModelPicker(dialog,gw,{title:s.kind==="main"?"Set main model":`Set auxiliary \xB7 ${s.label}`,onApply:async(prov,model)=>{let r=await assign(gw,s.key,prov,model);if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});if(toast.show({variant:"success",message:s.kind==="main"?`main \u2192 ${prov} \xB7 ${model}`:`${s.key} \u2192 ${prov} \xB7 ${model}`}),r.warning)toast.show({variant:"warning",message:r.warning});if(load4(),s.kind==="main")await warnStaleAux(prov)}})},[gw,dialog,toast,load4,managed,raw]),unset=import_react85.useCallback((s)=>{if(managed||s.kind!=="aux"||s.auto)return;resetAux(gw,s.key).then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:r.failed.map((f)=>f.err).join("; ")});toast.show({variant:"success",message:`${s.key} \u2192 auto`}),load4()})},[gw,toast,load4,managed]),unsetAll=import_react85.useCallback(()=>openConfirm(dialog,{title:"Reset all auxiliary slots to auto?",body:`${AUX_TASKS.length} slots. Each falls back to the main model.`,yes:"reset",danger:!0}).then((ok)=>{if(!ok)return;resetAux(gw,"all").then((r)=>{if(r.failed.length)return toast.show({variant:"error",message:`${r.failed.length} failed`});toast.show({variant:"success",message:"All auxiliary slots \u2192 auto"}),load4()})}),[gw,dialog,toast,load4]),keys=useKeys();if(useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(keys.match("config.mode",key3)&&!editing&&!searching){setMode((m2)=>m2==="form"?"yaml":"form");return}if(keys.match("config.save",key3))return void save2();if(mode==="yaml"){if(key3.name==="backspace"){setYaml((prev)=>prev.slice(0,-1));return}if(key3.name==="return"){setYaml((prev)=>prev+`
|
|
4147
4146
|
`);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setYaml((prev)=>prev+key3.raw);return}return}if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setCursor(0);return}if(key3.name==="backspace"){setQuery((prev)=>prev.slice(0,-1)),setCursor(0);return}if(key3.name==="up"){setCursor((c)=>Math.max(0,c-1));return}if(key3.name==="down"){setCursor((c)=>Math.min(count3-1,c+1));return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((prev)=>prev+key3.raw),setCursor(0);return}return}if(editing){let f2=fields[cursor];if(key3.name==="escape"){if(setEditing(!1),setBuf(""),f2)setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});return}if(key3.name==="return"){if(f2){let msg=check(f2.key,buf);if(msg){setErr((e)=>({...e,[f2.key]:msg}));return}setErr((e)=>{let{[f2.key]:_2,...rest}=e;return rest});let val=f2.type==="number"?Number(buf)||0:buf;update(f2.key,val)}setEditing(!1),setBuf("");return}if(key3.name==="backspace"){setBuf((prev)=>prev.slice(0,-1));return}if(key3.raw&&key3.raw.length===1){setBuf((prev)=>prev+key3.raw);return}return}if(key3.name==="tab"){setFocus((f2)=>f2==="categories"?"fields":"categories");return}if(keys.match("list.search",key3)){setSearching(!0),setQuery(""),setCursor(0);return}if(focus==="categories"){if(key3.name==="up"){setCat((c)=>{let n=Math.max(0,c-1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key3.name==="down"){setCat((c)=>{let n=Math.min(groups.length-1,c+1);return catFollow.opts.scrollTo(n),n}),setCursor(0);return}if(key3.name==="return"){setFocus("fields");return}return}if(onSlots){let s=slots[cursor];if(handleListKey(keys,key3,{count:count3,setSel:setCursor,...follow.opts,onActivate:s?()=>pick(s):void 0,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}})||!s)return;if(key3.raw==="x")return unset(s);if(key3.raw==="X")return void unsetAll();return}let f=fields[cursor],writable=!managed;if(handleListKey(keys,key3,{count:count3,setSel:setCursor,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onToggle:writable&&f?.type==="boolean"?()=>update(f.key,!f.value):void 0,onActivate:f&&writable&&(f.type==="string"||f.type==="number")?()=>{setEditing(!0),setBuf(String(f.value??""))}:void 0})||!f||!writable)return;if(f.type==="select"&&f.options){let idx=f.options.indexOf(String(f.value));if(key3.raw==="l"||key3.raw==="]"){update(f.key,f.options[(idx+1)%f.options.length]);return}if(key3.raw==="h"||key3.raw==="["){update(f.key,f.options[(idx-1+f.options.length)%f.options.length]);return}}}),mode==="yaml")return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(TabShell,{title:"Config \xB7 YAML",children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("text",{wrapMode:"word",children:[$jsx("span",{fg:theme.text,children:yaml}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})})}),$jsx(HintBar,{pairs:[[keys.print("config.mode"),"form"],[keys.print("config.save"),"save"]]})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,children:[searching?$jsx("box",{height:1,paddingLeft:1,paddingRight:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"\u2503 "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"}),$jsx("span",{fg:theme.textMuted,children:` ${count3} of ${all.length} \xB7 \u2191\u2193 nav \xB7 Esc close`})]})}):null,$jsxs("box",{flexDirection:"row",flexGrow:1,children:[searching?null:$jsx(TabShell,{title:"Config",grow:1,focus:focus==="categories",children:$jsx("scrollbox",{ref:catFollow.ref,scrollY:!0,flexGrow:1,children:groups.map((c,i)=>{let sel=i===cat,hot=sel&&focus==="categories",items=grouped.get(c)??[],n=c==="models"?slots.length:items.length,catDirty=items.some((f)=>changed(f.key));return $jsx("box",{id:catFollow.id(i),backgroundColor:hot?theme.backgroundElement:void 0,onMouseDown:()=>{setCat(i),setCursor(0),setFocus("categories")},children:$jsxs("text",{children:[$jsx("span",{fg:catDirty?theme.warning:theme.textMuted,children:catDirty?"\u25CF":" "}),$jsxs("span",{fg:hot?theme.accent:sel?theme.primary:theme.text,children:[sel?"\u25B8 ":" ",c]}),$jsx("span",{fg:theme.textMuted,children:` (${n})`})]})},c)})})}),$jsxs(TabShell,{title:onSlots?"models \xB7 applies immediately":searching?"Search":nChanged>0?`${active} \xB7 ${nChanged} unsaved`:active,grow:3,focus:focus==="fields"||searching,children:[managed?$jsxs("box",{height:1,flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.warning,children:"\uD83D\uDD12 managed install \u2014 edit"}),$jsx(FileLink,{source:makeSource("config.yaml"),children:"config.yaml"}),$jsx("text",{fg:theme.warning,children:"via configuration.nix"})]}):null,onSlots?$jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Auxiliary tasks handle side-jobs. 'auto' = use main model. Per-task api_key/base_url/timeout live in the 'auxiliary' category."})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:slots.map((s,i)=>$jsx(SlotRow,{id:follow.id(i),s,on:i===cursor&&focus==="fields"},s.key))})]},"slots"):$jsxs($Fragment,{children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),searching?$jsx(Col,{w:12,fg:theme.textMuted,bold:!0,children:"Category"}):null,$jsx(Col,{w:40,fg:theme.textMuted,bold:!0,children:"Field"}),$jsx(Col,{grow:!0,min:6,fg:theme.textMuted,bold:!0,children:"Value"}),$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:9,fg:theme.textMuted,children:""})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching fields":"No fields in this category"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{if(s.head!==null)acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",s.head," "]})},`\xA7${s.head}`));return s.items.forEach((f,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(FieldRow,{id:follow.id(i),field:f,active:i===cursor&&(focus==="fields"||searching),changed:changed(f.key),editing:editing&&i===cursor,buf,readonly:!!managed,error:err[f.key],badge:searching?groupOf(f.key):void 0},f.key))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]})]})]}),managed?$jsx(HintBar,{raw:`read-only \xB7 managed by ${managed}`}):onSlots?$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],["Enter","pick"],["x","reset"],["X","reset-all"],["Tab","categories"]]}):focus==="categories"&&!searching?$jsx(HintBar,{pairs:[["\u2191\u2193","select"],["Tab","fields"]]}):$jsx(HintBar,{pairs:[[keys.print("config.mode"),"yaml"],["Tab","categories"],["\u2191\u2193","nav"],[keys.print("list.search"),"search"],[keys.print("config.save"),"save"]],suffix:nChanged>0?`\u25CF ${nChanged} unsaved`:void 0})]})});var import_react89=__toESM(require_react_production(),1);var import_react87=__toESM(require_react_production(),1);var iso2=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},parseList=(stdout)=>stdout.split(`
|
|
4148
|
-
`).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state2=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react87.useState(null),[loaded,setLoaded]=import_react87.useState(!1),[busy,setBusy]=import_react87.useState(null),[archived,setArchived]=import_react87.useState([]),[mode,setMode]=import_react87.useState("report"),[sel,setSel]=import_react87.useState(0),sb=import_react87.useRef(null);import_react87.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react87.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code===0)setArchived(parseList(r.stdout))}).catch(()=>{})},[gw]);import_react87.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react87.useCallback((verb,ok)=>{if(busy)return;setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]),restore=import_react87.useCallback((name)=>{if(busy)return;setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${name}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]);useKeyboard((key3)=>{if(mode==="archived"){if(key3.name==="escape"){setMode("report");return}if(key3.raw==="a"){setMode("report");return}if(key3.name==="up")return setSel((s)=>Math.max(0,s-1));if(key3.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key3.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key3.name==="escape")return dialog.clear();if(key3.raw==="r")return sh("run","Curator run started (background)");if(key3.raw==="p")return state2?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key3.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react87.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last3=iso2(state2?.last_run_at??null),due=last3&&cfg?last3+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state2?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state2?`${state2.run_count} run${state2.run_count===1?"":"s"}${last3?" \xB7 last "+ago(last3):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last3?ago(last3):"never"],["Duration",state2?.last_run_duration_seconds?dur2(state2.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state2?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state2?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state2.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react89.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react89.memo((props)=>{let theme=useTheme().theme,on=props.selected;return $jsxs("box",{flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]})}),bycat=(skills)=>skills.reduce((map,s)=>{let cat=s.category||"uncategorized";return map.set(cat,[...map.get(cat)??[],s]),map},new Map),line3=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react89.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line3(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react89.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react89.memo((props)=>{let{theme,syntaxStyle}=useTheme(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react89.useState(()=>listCuratorRuns()),[sel,setSel]=import_react89.useState(0),[open2,setOpen]=import_react89.useState(!1),[body,setBody]=import_react89.useState(""),run=runs[sel];import_react89.useEffect(()=>{if(!open2||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open2,run?.id]);let moveSel=import_react89.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key3)=>{if(!props.focused)return;handleListKey(keys,key3,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open2?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react89.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react89.useRef(indexCuratorLineage());import_react89.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react89.useState([]),[selected,setSelected]=import_react89.useState(0),[searching,setSearching]=import_react89.useState(!1),[query,setQuery]=import_react89.useState(""),[hits,setHits]=import_react89.useState([]),[sort,setSort]=import_react89.useState("name"),[history,setHistory]=import_react89.useState(!1),seq=import_react89.useRef(0),load4=import_react89.useCallback(()=>{gw.request("skills.manage",{action:"list"}).then((res)=>{let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch(()=>{})},[gw]);import_react89.useEffect(()=>{load4()},[load4]),import_react89.useEffect(()=>{let id=++seq.current;if(!searching||!query.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch(()=>{if(seq.current===id)setHits([])})},150);return()=>clearTimeout(t2)},[gw,query,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):bycat(skills)].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react89.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react89.useCallback(async(name)=>{if(!await openConfirm(dialog,{title:"Install skill?",body:name,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:name}).then(()=>{toast.show({variant:"success",message:`Installed ${name}`}),exit(),load4()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load4]),keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){exit();return}if(key3.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key3.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key3.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key3.name==="return"){let hit=hits[selected];if(hit)install2(hit.name);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")setQuery((p)=>p+key3.raw),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="c"){openCurator(dialog);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key3.name==="escape")return setHistory(!1);return}handleListKey(keys,key3,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i)},h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row3,i)=>{if(row3.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row3.category}`})})},`h-${row3.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row3.skill,usage:usage[row3.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row3.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react91=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group2=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row2=import_react91.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react91.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react91.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react91.useState([]),[sel,setSel]=import_react91.useState(0),[err,setErr]=import_react91.useState(null),secs=group2(list2),flat=secs.flatMap((s)=>s.items),live=import_react91.useRef({flat,sel});live.current={flat,sel};let load4=import_react91.useCallback(()=>{gw.request("toolsets.list",{}).then((r)=>{setList(r.toolsets??[]),setErr(null)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react91.useEffect(()=>{load4()},[load4]);let toggle=import_react91.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let action=ts2.enabled?"disable":"enable",was=ts2.enabled;setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:!t2.enabled}:t2)),gw.request("tools.configure",{action,names:[ts2.name]}).then((r)=>{if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(Array.isArray(r.enabled_toolsets)){let on=new Set(r.enabled_toolsets);setList((prev)=>prev.map((t2)=>({...t2,enabled:on.has(t2.name)})))}else load4()}).catch((e)=>{setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"error",message:e.message})})},[gw,toast,load4]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row2,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react92=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react92.memo((props)=>{let theme=useTheme().theme,set2=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set2?theme.success:theme.textMuted,children:set2?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set2?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react92.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react92.useState(0),[reveal,setReveal]=import_react92.useState(new Set),[collapsed,setCollapsed]=import_react92.useState({}),[searching,setSearching]=import_react92.useState(!1),[query,setQuery]=import_react92.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key3)=>({type:"var",key:key3,value:vars[key3]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react92.useCallback(async(key3,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key3}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} saved`})},[dialog,toast]),add2=import_react92.useCallback(async()=>{let key3=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key3)return;let val=await openTextPrompt(dialog,{title:`Set ${key3}`,label:"Value"});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} added`})},[dialog,toast]),del=import_react92.useCallback(async(key3)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key3} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key3),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} removed`})},[dialog,toast]),revealAll=import_react92.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react92.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react92.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react92.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key3.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key3.name==="up")return setSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key3.name==="return")return setSearching(!1),activate();if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((q4)=>q4+key3.raw),setSel(0);return}return}handleListKey(keys,key3,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add2,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row3,i)=>row3.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row3.collapsed?"\u25B8":"\u25BE"} ${row3.category}`})})},`h-${row3.category}`):$jsx(VarRow,{id:follow.id(i),name:row3.key,value:row3.value,shown:reveal.has(row3.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row3.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react94=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react94.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react94.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has?"\u25D0":"\u25CB",fg2=pOn?theme.success:has?theme.warning:theme.textMuted,tag=pOn?"active":has?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react94.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react94.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react94.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react95.memo((props)=>{let labels=SUB_TABS[CONFIG_TAB];import_react95.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane3,{visible:props.sub===0,children:$jsx(Config,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react111=__toESM(require_react_production(),1);var import_react104=__toESM(require_react_production(),1);import{basename as basename12}from"path";var import_react96=__toESM(require_react_production(),1);var PathPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react96.useState(props.initial??""),[items,setItems]=import_react96.useState([]),seq=import_react96.useRef(0),ok=(it)=>it.meta==="dir"||!props.filter||props.filter.test(it.text);return import_react96.useEffect(()=>{if(!value.trim()){setItems([]);return}let me2=++seq.current,t2=setTimeout(()=>{props.gw.request("complete.path",{word:value}).then((r)=>{if(seq.current===me2)setItems((r.items??[]).filter(ok).slice(0,5))}).catch(()=>{if(seq.current===me2)setItems([])})},120);return()=>clearTimeout(t2)},[value,props.gw]),useKeyboard((key3)=>{if(key3.name!=="tab")return;key3.preventDefault();let hit=items[0];if(hit)setValue(hit.text)}),$jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),items.length>0?items.map((it)=>$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:it.text})}),it.meta?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:` ${it.meta}`})}):null]},it.text)):null,items.length>0?$jsx("box",{height:1}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?`Tab complete \xB7 Enter confirm \xB7 Esc cancel${items.length>0?` \xB7 ${items.length} match${items.length===1?"":"es"}`:""}`:"Type a path \xB7 Esc cancel"})})]})};function openPathPrompt(dialog,gw,opts){return new Promise((resolve4)=>{dialog.replace($jsx(PathPrompt,{title:opts.title,label:opts.label,initial:opts.initial,filter:opts.filter,gw,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var import_react98=__toESM(require_react_production(),1);var BASE=`
|
|
4149
|
-
high contrast, light subject on dark, black background`,BINDS=[{name:"return",action:"submit"},{name:"return",shift:!0,action:"newline"}],Generate=(props)=>{let theme=useTheme().theme,ta=import_react98.useRef(null),[prompt,setPrompt]=import_react98.useState(props.lastPrompt??BASE),[useSeed,setUseSeed]=import_react98.useState(!!props.seed),[secs,setSecs]=import_react98.useState(2),[busy,setBusy]=import_react98.useState(!1),[err,setErr]=import_react98.useState(null),[field,setField]=import_react98.useState("prompt");import_react98.useEffect(()=>{ta.current?.setCursor(0,0)},[]);let fields=props.kind==="video"?props.seed?["prompt","seed","seconds","submit"]:["prompt","seconds","submit"]:props.seed?["prompt","seed","submit"]:["prompt","submit"],advance=()=>setField((f)=>fields[(fields.indexOf(f)+1)%fields.length]),submit2=()=>{let p=prompt.trim(),bare=!props.lastPrompt&&p===BASE.trim();if(!p||bare||busy){if(bare)setErr("describe the subject on line 1");return}setBusy(!0),setErr(null),props.run(props.kind,p,{seed:props.seed&&useSeed?props.seed:void 0,seconds:props.kind==="video"?secs:void 0,aspect:props.kind==="video"?"1:1":"square"}).then((r)=>{if("err"in r){setErr(r.err),setBusy(!1);return}props.onDone(r.path,p)})};useKeyboard((key3)=>{if(busy)return;if(key3.name==="tab"){key3.preventDefault();let i=fields.indexOf(field),next2=fields[(i+(key3.shift?fields.length-1:1))%fields.length];setField(next2);return}if(field==="prompt")return;if(key3.name==="return")return field==="submit"?submit2():advance();if(field==="seed"&&(key3.name==="space"||key3.name==="left"||key3.name==="right")){setUseSeed((v2)=>!v2);return}if(field==="seconds"){if(key3.name==="left")return setSecs((v2)=>Math.max(1,v2-1));if(key3.name==="right")return setSecs((v2)=>Math.min(4,v2+1))}if(field==="submit"&&key3.name==="space")submit2()});let lbl=(id,text3)=>$jsx("box",{width:12,flexShrink:0,children:$jsxs("text",{fg:field===id?theme.accent:theme.textMuted,children:[field===id?"\u25B8 ":" ",text3]})});return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Generate ${props.kind} \u2014 ${props.state}`})})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",children:[lbl("prompt","Prompt"),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("textarea",{ref:ta,initialValue:prompt,keyBindings:BINDS,onSubmit:advance,onContentChange:()=>{if(ta.current)setPrompt(ta.current.plainText)},focused:field==="prompt",placeholder:props.kind==="image"?"describe the image\u2026":"describe the motion\u2026",textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field==="prompt"?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement,minHeight:4,maxHeight:6})})]}),props.seed?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seed","Seed"),$jsx("box",{flexGrow:1,minWidth:0,height:1,children:$jsx("text",{fg:field==="seed"?theme.text:theme.textMuted,children:useSeed?"\u25CF base.png":"\u25CB none"})})]}):null,props.kind==="video"?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seconds","Seconds"),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:1,max:4,value:secs,foregroundColor:field==="seconds"?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>setSecs(Math.round(v2))})}),$jsx("box",{width:6,height:1,children:$jsx("text",{fg:field==="seconds"?theme.text:theme.textMuted,children:` ${secs}s`})})]}):null,$jsxs("box",{marginTop:1,flexDirection:"row",children:[lbl("submit",""),$jsx("box",{flexGrow:1,minWidth:0,children:busy?$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:"generating\u2026"})}):err?$jsx("text",{fg:theme.warning,wrapMode:"word",children:err}):$jsx("box",{height:1,children:$jsx("text",{fg:field==="submit"?theme.accent:theme.textMuted,children:"[Enter] generate"})})})]}),$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter next \xB7 Shift+Enter newline \xB7 Tab field \xB7 Esc cancel"})})]})};function openGenerate(dialog,run,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Generate,{...opts,run,onDone:(p,txt)=>{resolve4(p?{path:p,prompt:txt}:null),dialog.clear()}}),()=>resolve4(null))})}var import_react100=__toESM(require_react_production(),1);import{existsSync as existsSync18,readFileSync as readFileSync11}from"fs";import{dirname as dirname12,join as join15}from"path";var exports_eikon={};__export(exports_eikon,{writeStudio:()=>writeStudio,useInstalled:()=>useInstalled,update:()=>update,studioFile:()=>studioFile,sourceStatus:()=>sourceStatus,sourceStamp:()=>sourceStamp,sourceName:()=>sourceName,sourceFetchUrl:()=>sourceFetchUrl,sourceExt:()=>sourceExt,sourceDir:()=>sourceDir,save:()=>save2,revision:()=>revision,remove:()=>remove2,register:()=>register,readStudio:()=>readStudio,raw:()=>raw,rasterizers:()=>rasterizers,rasterizer:()=>rasterizer,probe:()=>probe,previewPackage:()=>previewPackage,pick:()=>pick,peekSource:()=>peekSource,parseEikonFile:()=>parseEikonFile,parseEikon:()=>parseEikon,onRevision:()=>onRevision,onRegistry:()=>onRegistry,notifyRevision:()=>notifyRevision,localSources:()=>localSources,loadCatalog:()=>loadCatalog2,list:()=>list2,lifecycle:()=>lifecycle,installPackage:()=>installPackage,inspectSource:()=>inspectSource,header:()=>header,hasLocalSource:()=>hasLocalSource,findSource:()=>findSource,file:()=>file,fetchSource:()=>fetchSource,ensure:()=>ensure,eikon:()=>exports_eikon,downloadSource:()=>downloadSource,dir:()=>dir,baked:()=>baked,attachSources:()=>attachSources,adopt:()=>adopt,adaptPackage:()=>adaptPackage});import{existsSync as existsSync17,mkdirSync as mkdirSync4,readdirSync as readdirSync6,copyFileSync as copyFileSync2,readFileSync as readFileSync10,writeFileSync as writeFileSync5,rmSync as rmSync3,statSync as statSync6,renameSync as renameSync3}from"fs";import{createHash as createHash3}from"crypto";import{join as join14,extname as extname3,basename as basename11,dirname as dirname11}from"path";import{existsSync as existsSync16,readFileSync as readFileSync9}from"fs";import{join as join13,dirname as dirname10}from"path";var locate2=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join13(d2,"assets/eikons");if(existsSync16(p))return p;let up=dirname10(d2);if(up===d2)break;d2=up}return join13(import.meta.dir,"../../../assets/eikons")},BUNDLED_EIKON_DIR=locate2(),packageEntrypoint=(dir)=>{let manifest2=join13(dir,"manifest.json");if(!existsSync16(manifest2))return;try{let entrypoints=JSON.parse(readFileSync9(manifest2,"utf8")).entrypoints,value=entrypoints&&typeof entrypoints==="object"&&!Array.isArray(entrypoints)?entrypoints.default:void 0,path7=typeof value==="string"?join13(dir,value):void 0;return path7&&existsSync16(path7)?path7:void 0}catch{return}};function bundledEikonPath(name){if(!name)return;let id=name==="default"?"nous":name,dir=join13(BUNDLED_EIKON_DIR,id),entry2=packageEntrypoint(dir);if(entry2)return entry2;for(let p of[join13(dir,`${id}.eikon`),join13(BUNDLED_EIKON_DIR,`${id}.eikon`)])if(existsSync16(p))return p;return}import{deflateSync}from"zlib";import{spawnSync as spawnSync2}from"child_process";import{statSync as statSync5}from"fs";var W2=48,H=24,FPS0=16,MAXF=256,S0={zoom:1,ox:0.5,oy:0.5},T0={contrast:1,invert:!0,flip:"none"},defaults=(r)=>Object.fromEntries(Object.entries(r.knobs).map(([k2,d2])=>[k2,d2.default])),caps2={chafa:chafaBin(),ffmpeg:spawnSync2("ffmpeg",["-version"],{stdio:"ignore"}).status===0,ffprobe:spawnSync2("ffprobe",["-version"],{stdio:"ignore"}).status===0};function probe(path7){if(!caps2.ffprobe)return null;let r=spawnSync2("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",path7],{encoding:"utf8"});if(r.status!==0)return null;let m2=r.stdout.trim().match(/^(\d+),(\d+)/);return m2?{w:+m2[1],h:+m2[2]}:null}var clamp=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),SCALE=384,PLANE=SCALE*SCALE,VID=/\.(mp4|webm|mov|mkv|m4v|gif)$/i,clips=new Map,CLIP_CAP=8;function decode2(src3,fps=FPS0){let full=resolveImage(src3);if(!full)return Promise.resolve(`not found: ${src3}`);let mt=statSync5(full,{throwIfNoEntry:!1})?.mtimeMs??0,key3=`${full}:${mt}:${fps}`,got=clips.get(key3);if(got)return clips.delete(key3),clips.set(key3,got),got;if(!caps2.ffmpeg)return Promise.resolve("ffmpeg not installed");let video=VID.test(full),vf=[...video?[`fps=${fps}`]:[],`scale=${SCALE}:${SCALE}:force_original_aspect_ratio=increase`,`crop=${SCALE}:${SCALE}`].join(","),p=(async()=>{let ff=Bun.spawn(["ffmpeg","-hide_banner","-loglevel","error","-i",full,"-vf",vf,"-frames:v",video?String(MAXF):"1","-f","rawvideo","-pix_fmt","gray","-"],{stdout:"pipe",stderr:"pipe"}),[buf,err]=await Promise.all([new Response(ff.stdout).arrayBuffer().then((b2)=>new Uint8Array(b2)),new Response(ff.stderr).text()]);if(await ff.exited,ff.exitCode!==0)return`ffmpeg: ${err.trim()||"failed"}`;if(buf.length===0||buf.length%PLANE!==0)return`ffmpeg: bad read (${buf.length})`;let n=buf.length/PLANE;return{planes:Array.from({length:n},(_2,i)=>buf.subarray(i*PLANE,(i+1)*PLANE)),fps:video?fps:0,w:SCALE,h:SCALE}})();if(clips.size>=CLIP_CAP)clips.delete(clips.keys().next().value);return clips.set(key3,p),p}var prewarm=(src3,fps=FPS0)=>void decode2(src3,fps);function crop(clip,sp){let side=Math.max(1,Math.round(clip.w*clamp(sp.zoom,0.1,1))),x0=Math.round((clip.w-side)*clamp(sp.ox,0,1)),y0=Math.round((clip.h-side)*clamp(sp.oy,0,1)),n=clip.planes.length,gray=new Uint8Array(side*side*n);for(let f=0;f<n;f++){let pl=clip.planes[f],off=f*side*side;for(let y2=0;y2<side;y2++)gray.set(pl.subarray((y0+y2)*clip.w+x0,(y0+y2)*clip.w+x0+side),off+y2*side)}let enc2;return{gray,w:side,h:side,frames:n,png:()=>enc2??=png(gray,side,side*n)}}function png(gray,w2,h2){let be32=(n)=>new Uint8Array([n>>>24,n>>>16&255,n>>>8&255,n&255]),T2=png_crc,crc=(b2)=>{let c=4294967295;for(let i=0;i<b2.length;i++)c=T2[(c^b2[i])&255]^c>>>8;return~c>>>0},chunk=(tag,data2)=>{let t2=new TextEncoder().encode(tag),body=new Uint8Array(t2.length+data2.length);return body.set(t2),body.set(data2,4),[be32(data2.length),body,be32(crc(body))]},ihdr=new Uint8Array(13);ihdr.set(be32(w2),0),ihdr.set(be32(h2),4),ihdr[8]=8,ihdr[9]=0,ihdr[10]=0,ihdr[11]=0,ihdr[12]=0;let raw=new Uint8Array(h2*(w2+1));for(let y2=0;y2<h2;y2++)raw.set(gray.subarray(y2*w2,(y2+1)*w2),y2*(w2+1)+1);let idat=new Uint8Array(deflateSync(raw,{level:1})),parts2=[new Uint8Array([137,80,78,71,13,10,26,10]),...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))],out=new Uint8Array(parts2.reduce((n,p)=>n+p.length,0)),o=0;for(let p of parts2)out.set(p,o),o+=p.length;return out}var png_crc=(()=>{let t2=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k2=0;k2<8;k2++)c=c&1?3988292384^c>>>1:c>>>1;t2[n]=c>>>0}return t2})(),cache4=new Map,CAP3=256;function put(key3,v2){if(cache4.size>=CAP3)cache4.delete(cache4.keys().next().value);return cache4.set(key3,v2),v2}function hit(key3){let v2=cache4.get(key3);if(!v2)return;return cache4.delete(key3),cache4.set(key3,v2),v2}function resetCache(){cache4.clear(),clips.clear()}var keyOf=(r,src3,sp,tn,fps,k2)=>`${r}|${src3}|${fps}|${sp.zoom.toFixed(3)}:${sp.ox.toFixed(3)}:${sp.oy.toFixed(3)}|${tn.contrast.toFixed(2)}:${+tn.invert}:${tn.flip}|${JSON.stringify(k2)}`;async function cached2(r,src3,sp,tn,fps,k2,signal){let key3=keyOf(r.name,src3,sp,tn,fps,k2),got=hit(key3);if(got)return{frames:got};let cl=await decode2(src3,fps);if(typeof cl==="string")return{err:cl};if(signal?.aborted)return{err:"aborted"};let out=await r.render(tone(crop(cl,sp),tn),k2,signal);if("err"in out)return out;if(signal?.aborted)return{err:"aborted"};return{frames:put(key3,out.frames)}}function pad(rows3){let out=rows3.slice(0,H);while(out.length<H)out.push("");return out.map((l)=>{if(l.includes("\x1B["))return l;let cp=Array.from(l);return cp.length>=W2?cp.slice(0,W2).join(""):l+" ".repeat(W2-cp.length)})}function box(out,n){let rows3=out.replace(/\n$/,"").split(`
|
|
4147
|
+
`).map((s)=>s.trim()).filter((s)=>s.length>0&&!s.startsWith("(")),CuratorDialog=()=>{let{theme,syntaxStyle}=useTheme(),gw=useGateway(),toast=useToast(),dialog=useDialog(),state2=useHome("curatorState"),cfg=useHome("config")?.curator,[report2,setReport]=import_react87.useState(null),[loaded,setLoaded]=import_react87.useState(!1),[busy,setBusy]=import_react87.useState(null),[archived,setArchived]=import_react87.useState([]),[mode,setMode]=import_react87.useState("report"),[sel,setSel]=import_react87.useState(0),sb=import_react87.useRef(null);import_react87.useEffect(()=>{readLatestCuratorReport().then((r)=>{setReport(r),setLoaded(!0)}).catch(()=>setLoaded(!0))},[]);let refreshArchived=import_react87.useCallback(()=>{gw.request("shell.exec",{command:"hermes curator list-archived"}).then((r)=>{if(r.code===0)setArchived(parseList(r.stdout))}).catch(()=>{})},[gw]);import_react87.useEffect(()=>{refreshArchived()},[refreshArchived]);let sh=import_react87.useCallback((verb,ok)=>{if(busy)return;setBusy(verb),gw.request("shell.exec",{command:`hermes curator ${verb}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:ok}),home2.invalidate("curatorState")}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]),restore=import_react87.useCallback((name)=>{if(busy)return;setBusy("restore"),gw.request("shell.exec",{command:`hermes curator restore ${name}`}).then((r)=>{if(r.code!==0)throw Error((r.stderr||r.stdout||`exit ${r.code}`).trim());toast.show({variant:"success",message:`Restored ${name}`}),setArchived((prev)=>prev.filter((n)=>n!==name)),setSel((s)=>Math.max(0,s-1))}).catch((e)=>toast.show({variant:"error",message:trunc5(e.message,120)})).finally(()=>setBusy(null))},[gw,toast,busy]);useKeyboard((key3)=>{if(mode==="archived"){if(key3.name==="escape"){setMode("report");return}if(key3.raw==="a"){setMode("report");return}if(key3.name==="up")return setSel((s)=>Math.max(0,s-1));if(key3.name==="down")return setSel((s)=>Math.min(archived.length-1,s+1));if(key3.name==="return"){let name=archived[sel];if(name)restore(name);return}return}if(key3.name==="escape")return dialog.clear();if(key3.raw==="r")return sh("run","Curator run started (background)");if(key3.raw==="p")return state2?.paused?sh("resume","Curator resumed"):sh("pause","Curator paused");if(key3.raw==="a"&&archived.length>0)setSel(0),setMode("archived")}),import_react87.useEffect(()=>{if(mode==="archived")sb.current?.scrollChildIntoView(`arch-${sel}`)},[sel,mode]);let last3=iso2(state2?.last_run_at??null),due=last3&&cfg?last3+cfg.interval_hours*3600:null,status=cfg?.enabled===!1?"disabled":state2?.paused?"paused":"enabled",tint=status==="enabled"?theme.success:status==="paused"?theme.warning:theme.textMuted;return $jsxs("box",{flexDirection:"column",width:120,height:34,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Curator"})}),$jsx("span",{fg:tint,children:` \xB7 ${status}`})]}),busy?$jsx("box",{marginLeft:2,children:$jsx(Spinner,{color:theme.textMuted,label:busy})}):null]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:state2?`${state2.run_count} run${state2.run_count===1?"":"s"}${last3?" \xB7 last "+ago(last3):" \xB7 never"} \xB7 Esc to close`:"No curator state yet \xB7 Esc to close"})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:40,height:"100%",flexShrink:0,children:[$jsx(KVBlock,{rows:[["Next run",status!=="enabled"?`\u2014 (${status})`:due?until(due):"when idle"],["Last run",last3?ago(last3):"never"],["Duration",state2?.last_run_duration_seconds?dur2(state2.last_run_duration_seconds):void 0],["Archived",archived.length>0?String(archived.length):void 0]]}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Config \xB7 edit in Config tab"})}),$jsx(KVBlock,{rows:[["Interval",cfg?`${cfg.interval_hours}h`:"\u2014"],["Stale after",cfg?`${cfg.stale_after_days}d`:"\u2014"],["Archive after",cfg?`${cfg.archive_after_days}d`:"\u2014"]]}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"r "}),$jsx("span",{fg:theme.text,children:"run now"}),$jsx("span",{fg:theme.textMuted,children:" (background)"})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"p "}),$jsx("span",{fg:theme.text,children:state2?.paused?"resume":"pause"})]})}),archived.length>0?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"a "}),$jsx("span",{fg:theme.text,children:"archived skills"}),$jsx("span",{fg:theme.textMuted,children:` (${archived.length})`})]})}):null]}),state2?.last_run_summary?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Last run"})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("markdown",{content:state2.last_run_summary,fg:theme.markdownText,syntaxStyle})})]}):null]}),mode==="archived"?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Archived skills (${archived.length})`})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191\u2193 select \xB7 Enter restore \xB7 a/Esc back to report"})}),$jsx("box",{height:1}),$jsx("scrollbox",{ref:sb,scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,contentOptions:{flexDirection:"column"},children:archived.length===0?$jsx("text",{fg:theme.textMuted,children:"No archived skills."}):archived.map((name,i)=>$jsx("box",{id:`arch-${i}`,height:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>restore(name),children:$jsxs("text",{fg:i===sel?theme.text:theme.textMuted,children:[i===sel?"\u25B8 ":" ",name]})},name))})]}):!loaded?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading report\u2026"})}):report2?$jsxs("box",{flexDirection:"column",flexGrow:1,height:"100%",minWidth:0,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE Report \xB7 ${report2.runId}`})})}),$jsx(KVLink,{label:"File",source:report2.source,text:report2.source.relative}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,border:!0,borderColor:theme.border,paddingLeft:1,paddingRight:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx("markdown",{content:report2.content||"(empty)",fg:theme.markdownText,syntaxStyle})})})]}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No runs yet \u2014 curator has not completed a cycle."})})]})]})},openCurator=(dialog)=>dialog.replace($jsx(CuratorDialog,{}),void 0,{ownCancel:!0});var NO_EVENTS=[],iso3=(s)=>{if(!s)return null;let t2=Date.parse(s);return Number.isFinite(t2)?Math.floor(t2/1000):null},SkillRow=import_react89.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,bg2=props.selected?theme.backgroundElement:void 0,used=iso3(u3?.last_used_at)??iso3(u3?.last_viewed_at),stale=u3?.state==="stale",archived=u3?.state==="archived";return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:theme.warning,children:u3?.pinned?"\uD83D\uDCCC":" "}),$jsx(Marquee,{grow:!0,min:8,active:props.selected,fg:archived?theme.textMuted:props.selected?theme.accent:theme.text,children:s.name}),archived?$jsx(Col,{w:10,fg:theme.textMuted,children:"archived"}):stale?$jsx(Col,{w:10,fg:theme.warning,children:"stale"}):$jsx(Col,{w:10,fg:theme.textMuted,children:used?ago(used):""})]})}),HitRow=import_react89.memo((props)=>{let theme=useTheme().theme,on=props.selected;return $jsxs("box",{flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:on?theme.accent:theme.text,children:props.hit.name}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,children:props.hit.description||"\u2014"})]})}),bycat=(skills)=>skills.reduce((map,s)=>{let cat=s.category||"uncategorized";return map.set(cat,[...map.get(cat)??[],s]),map},new Map),line3=(e)=>{switch(e.kind){case"absorbed":return`absorbed ${e.sources.map((s)=>`\`${s}\``).join(", ")}`;case"merged":return`merged into \`${e.into}\`${e.reason?` \u2014 ${e.reason}`:""}`;case"transition":return`${e.from} \u2192 ${e.to}`;case"pruned":return`pruned${e.reason?` \u2014 ${e.reason}`:""}`;case"added":return"created by curator"}},DetailPanel2=import_react89.memo((props)=>{let theme=useTheme().theme,s=props.skill,u3=props.usage,used=iso3(u3?.last_used_at),viewed=iso3(u3?.last_viewed_at),patched=iso3(u3?.last_patched_at);return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Skill Detail"})}),u3?.pinned?$jsx("span",{fg:theme.warning,children:" \uD83D\uDCCC pinned"}):null,u3?.state==="stale"?$jsx("span",{fg:theme.warning,children:" \xB7 stale"}):null,u3?.state==="archived"?$jsx("span",{fg:theme.textMuted,children:" \xB7 archived"}):null]})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:s.name})})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Category",s.category||"uncategorized",theme.info],["Tags",s.tags.length>0?s.tags.join(", "):void 0],u3?["Used",u3.use_count>0?`${u3.use_count}\xD7 \xB7 last ${used?ago(used):"never"}`:"never"]:null,u3&&viewed?["Viewed",`${u3.view_count}\xD7 \xB7 last ${ago(viewed)}`]:null,u3&&patched?["Patched",`${u3.patch_count}\xD7 \xB7 last ${ago(patched)}`]:null].filter(Boolean)}),$jsx(KVLink,{label:"File",source:s.source,text:s.source.relative}),$jsx("box",{height:1}),s.description?$jsx("text",{wrapMode:"word",children:$jsx("span",{fg:theme.text,children:s.description})}):$jsx("text",{fg:theme.textMuted,children:"No description"}),props.events.length>0?$jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Curator lineage"})}),props.events.map((e,i)=>$jsxs("box",{flexDirection:"row",minHeight:1,children:[$jsx("box",{width:10,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:ago(e.at)})}),$jsx("box",{flexGrow:1,minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:line3(e)})})]},i))]}):u3?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No curator events for this skill"})}):null]})}),EmptyState=import_react89.memo((props)=>{let theme=useTheme().theme;return $jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:props.searching?"No matching skills on hub":"No skills found in ~/.hermes/skills/"})})})}),HistoryPanel=import_react89.memo((props)=>{let{theme,syntaxStyle}=useTheme(),keys=useKeys(),follow=useFollow("skills-history"),[runs,setRuns]=import_react89.useState(()=>listCuratorRuns()),[sel,setSel]=import_react89.useState(0),[open2,setOpen]=import_react89.useState(!1),[body,setBody]=import_react89.useState(""),run=runs[sel];import_react89.useEffect(()=>{if(!open2||!run)return;let live=!0;return readCuratorReport(run.id).then((t2)=>{if(live)setBody(t2)}),()=>{live=!1}},[open2,run?.id]);let moveSel=import_react89.useCallback((v2)=>{setOpen(!1),setSel(v2)},[]);return useKeyboard((key3)=>{if(!props.focused)return;handleListKey(keys,key3,{count:runs.length,setSel:moveSel,...follow.opts,onActivate:()=>setOpen((o)=>!o),onRefresh:()=>setRuns(listCuratorRuns())})}),$jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:props.focused?theme.primary:theme.border,backgroundColor:theme.backgroundPanel,width:"50%",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Curator History"})}),$jsx("span",{fg:theme.textMuted,children:` ${runs.length} run${runs.length===1?"":"s"}${runs[0]?` \xB7 last ${ago(runs[0].at)}`:""}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select \xB7 Enter expand \xB7 ${keys.print("list.refresh")} reload \xB7 h close`})}),$jsx("box",{height:1}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:"no runs in ~/.hermes/logs/curator/"}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:runs.map((r,i)=>{let on=i===sel;return $jsxs("box",{id:follow.id(i),flexDirection:"column",children:[$jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),setOpen((o)=>i===sel?!o:!0)},children:[$jsx(Col,{w:2,fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx(Col,{w:12,fg:on?theme.accent:theme.text,children:ago(r.at)}),$jsx(Col,{grow:!0,fg:theme.textMuted,children:`${r.before}\u2192${r.after} arch ${r.archived} cons ${r.consolidated}${r.added?` +${r.added}`:""}`})]}),on&&open2?$jsx("box",{marginLeft:2,marginTop:1,marginBottom:1,children:$jsx("markdown",{content:body||"\u2026",fg:theme.markdownText,syntaxStyle})}):null]},r.id)})})})]})}),Skills=import_react89.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),usage=useHome("skillUsage")??{},curator=useHome("curatorState"),lineage2=import_react89.useRef(indexCuratorLineage());import_react89.useEffect(()=>{lineage2.current=indexCuratorLineage()},[curator?.run_count]);let[skills,setSkills]=import_react89.useState([]),[selected,setSelected]=import_react89.useState(0),[searching,setSearching]=import_react89.useState(!1),[query,setQuery]=import_react89.useState(""),[hits,setHits]=import_react89.useState([]),[sort,setSort]=import_react89.useState("name"),[history,setHistory]=import_react89.useState(!1),seq=import_react89.useRef(0),load4=import_react89.useCallback(()=>{gw.request("skills.manage",{action:"list"}).then((res)=>{let raw=res.skills??{},rows3=Object.entries(raw).flatMap(([cat,names])=>names.map((n)=>{let source=makeSource(`skills/${cat}/${n}/SKILL.md`,`${n}/SKILL.md`),fm=readSkillFrontmatter(source);return{source,category:cat,name:n,description:fm.description,tags:fm.tags,tokenEstimate:count2(`${n} ${fm.description}`)}}));rows3.sort((a,b2)=>a.source.relative.localeCompare(b2.source.relative)),setSkills(rows3)}).catch(()=>{})},[gw]);import_react89.useEffect(()=>{load4()},[load4]),import_react89.useEffect(()=>{let id=++seq.current;if(!searching||!query.trim()){setHits([]);return}let t2=setTimeout(()=>{gw.request("skills.manage",{action:"search",query}).then((r)=>{if(seq.current!==id)return;setHits(r.results??[]),setSelected(0)}).catch(()=>{if(seq.current===id)setHits([])})},150);return()=>clearTimeout(t2)},[gw,query,searching]);let flat=[...sort==="used"?new Map([["by recency",[...skills].sort((a,b2)=>{let ta=iso3(usage[a.name]?.last_used_at)??iso3(usage[a.name]?.last_viewed_at)??0;return(iso3(usage[b2.name]?.last_used_at)??iso3(usage[b2.name]?.last_viewed_at)??0)-ta})]]):bycat(skills)].flatMap(([cat,items])=>[{type:"header",category:cat},...items.map((s)=>({type:"skill",skill:s}))]),skillRows=flat.filter((r)=>r.type==="skill"),count3=searching?hits.length:skillRows.length,current=!searching&&skillRows[selected]?.type==="skill"?skillRows[selected].skill:null,follow=useFollow("sk"),exit=import_react89.useCallback(()=>{setSearching(!1),setQuery(""),setHits([]),setSelected(0)},[]),install2=import_react89.useCallback(async(name)=>{if(!await openConfirm(dialog,{title:"Install skill?",body:name,yes:"install"}))return;gw.request("skills.manage",{action:"install",query:name}).then(()=>{toast.show({variant:"success",message:`Installed ${name}`}),exit(),load4()}).catch((e)=>toast.show({variant:"error",message:`Install failed: ${e.message}`}))},[dialog,gw,toast,exit,load4]),keys=useKeys();useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){exit();return}if(key3.name==="backspace"){setQuery((p)=>p.slice(0,-1)),setSelected(0);return}if(key3.name==="up")return setSelected((p)=>Math.max(0,p-1));if(key3.name==="down")return setSelected((p)=>Math.min(count3-1,p+1));if(key3.name==="return"){let hit=hits[selected];if(hit)install2(hit.name);return}if(key3.raw&&key3.raw.length===1&&key3.raw>=" ")setQuery((p)=>p+key3.raw),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="s"){setSort((p)=>p==="name"?"used":"name"),setSelected(0);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="c"){openCurator(dialog);return}if(!key3.ctrl&&!key3.meta&&key3.raw==="h"){setHistory((h2)=>!h2);return}if(history){if(key3.name==="escape")return setHistory(!1);return}handleListKey(keys,key3,{count:count3,setSel:setSelected,...follow.opts,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})},onSearch:()=>{setSearching(!0),setQuery(""),setHits([]),setSelected(0)}})});let skillIdx=-1;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:searching?`Hub Search (${hits.length})`:`Skills (${skills.length}${sort==="used"?" \xB7 by use":""})`,children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,searching?null:$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,min:8,fg:theme.textMuted,bold:!0,children:"Name"})]}),searching?null:$jsx("box",{height:1}),count3===0?$jsx(EmptyState,{searching}):searching?$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:hits.map((h2,i)=>$jsx(HitRow,{hit:h2,selected:i===selected,onHover:()=>setSelected(i)},h2.name))})}):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:flat.map((row3,i)=>{if(row3.type==="header")return $jsx("box",{marginTop:i>0?1:0,children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`\u25BE ${row3.category}`})})},`h-${row3.category}`);skillIdx++;let idx=skillIdx;return $jsx(SkillRow,{id:follow.id(idx),skill:row3.skill,usage:usage[row3.skill.name],selected:idx===selected,onSelect:()=>setSelected(idx),onHover:()=>setSelected(idx)},row3.skill.name)})}),!searching&&curator?$jsx("box",{height:1,flexShrink:0,children:$jsxs("text",{children:[$jsx("span",{fg:theme.textMuted,children:"curator \xB7 "}),curator.paused?$jsx("span",{fg:theme.warning,children:"paused"}):curator.last_run_at?$jsx("span",{fg:theme.textMuted,children:`${curator.run_count} run${curator.run_count===1?"":"s"} \xB7 last ${ago(iso3(curator.last_run_at)??0)}`}):$jsx("span",{fg:theme.textMuted,children:"never run"})]})}):null]}),history?$jsx(HistoryPanel,{focused:!!props.focused&&!searching}):current?$jsx(DetailPanel2,{skill:current,usage:usage[current.name],events:lineage2.current.get(current.name)??NO_EVENTS}):null]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","navigate"],["Enter","install"],["Esc","cancel"]]:[["\u2191\u2193","navigate"],[keys.print("list.search"),"search hub"],["s","sort"],["c","curator"],["h","history"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react91=__toESM(require_react_production(),1);var kindOf=(ts)=>ts.name.includes(":")?"mcp":ts.name.startsWith("hermes-")?"platform":"core",KIND_LABEL={core:"core",platform:"platform bundles",mcp:"mcp"},group2=(list2)=>{let by={core:[],platform:[],mcp:[]};for(let ts of list2)by[kindOf(ts)].push(ts);return["core","platform","mcp"].filter((k2)=>by[k2].length>0).map((k2)=>({kind:k2,items:by[k2]}))},Row2=import_react91.memo((props)=>{let theme=useTheme().theme,ts=props.ts,bg2=props.selected?theme.backgroundElement:void 0,unavail=ts.available===!1,glyph=unavail?"\u25CC":ts.enabled?"\u25CF":"\u25CB",glyphFg=unavail?theme.warning:ts.enabled?theme.success:theme.textMuted;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onSelect,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:2,fg:glyphFg,children:`${glyph} `}),$jsx(Col,{grow:!0,fg:props.selected?theme.accent:theme.text,children:ts.name}),$jsx(Col,{w:9,fg:theme.info,right:!0,children:`${ts.tool_count} tools`})]})}),DetailPanel3=import_react91.memo((props)=>{let theme=useTheme().theme,ts=props.ts,unavail=ts.available===!1;return $jsxs("box",{flexDirection:"column",padding:1,border:!0,borderColor:theme.border,backgroundColor:theme.backgroundPanel,width:"40%",children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:ts.name})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:KIND_LABEL[kindOf(ts)]})}),$jsx("box",{height:1}),$jsx(KVBlock,{rows:[["Status",unavail?"unavailable":ts.enabled?"enabled":"disabled",unavail?theme.warning:ts.enabled?theme.success:theme.textMuted],["Tools",String(ts.tool_count),theme.info],["Includes",ts.includes?.length?ts.includes.join(", "):void 0,theme.text],["Requires",ts.requirements?.length?ts.requirements.join(", "):void 0,unavail?theme.warning:theme.text]]}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.text,children:ts.description||"\u2014"})}),ts.tools?.length?$jsxs($Fragment,{children:[$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:["Tools (",ts.tools.length,"):"]})}),$jsx("scrollbox",{flexGrow:1,scrollY:!0,children:ts.tools.map((n)=>$jsxs("text",{fg:theme.text,children:["\xB7 ",n]},n))})]}):null]})}),Toolsets=import_react91.memo((props)=>{let theme=useTheme().theme,gw=useGateway(),dialog=useDialog(),toast=useToast(),[list2,setList]=import_react91.useState([]),[sel,setSel]=import_react91.useState(0),[err,setErr]=import_react91.useState(null),secs=group2(list2),flat=secs.flatMap((s)=>s.items),live=import_react91.useRef({flat,sel});live.current={flat,sel};let load4=import_react91.useCallback(()=>{gw.request("toolsets.list",{}).then((r)=>{setList(r.toolsets??[]),setErr(null)}).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]);import_react91.useEffect(()=>{load4()},[load4]);let toggle=import_react91.useCallback(()=>{let ts2=live.current.flat[live.current.sel];if(!ts2)return;if(ts2.available===!1){toast.show({variant:"warning",message:`${ts2.name} is unavailable`});return}let action=ts2.enabled?"disable":"enable",was=ts2.enabled;setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:!t2.enabled}:t2)),gw.request("tools.configure",{action,names:[ts2.name]}).then((r)=>{if(r.unknown?.includes(ts2.name)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`${ts2.name} is not configurable`});return}if(r.missing_servers?.length&&ts2.name.includes(":")){let server=ts2.name.split(":",1)[0];if(r.missing_servers.includes(server)){setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"warning",message:`MCP server '${server}' not in config`});return}}if(Array.isArray(r.enabled_toolsets)){let on=new Set(r.enabled_toolsets);setList((prev)=>prev.map((t2)=>({...t2,enabled:on.has(t2.name)})))}else load4()}).catch((e)=>{setList((prev)=>prev.map((t2)=>t2.name===ts2.name?{...t2,enabled:was}:t2)),toast.show({variant:"error",message:e.message})})},[gw,toast,load4]),count3=flat.length,ts=flat[sel]??null,follow=useFollow("ts"),keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:count3,setSel,...follow.opts,onToggle:toggle,onRefresh:()=>{load4(),toast.show({variant:"info",message:"Reloaded",duration:1000})}});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs(TabShell,{title:`Toolsets (${count3})`,error:err,children:[$jsxs(Hdr,{children:[$jsx(Col,{w:4,fg:theme.textMuted,children:""}),$jsx(Col,{grow:!0,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:9,fg:theme.textMuted,bold:!0,right:!0,children:"Tools"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:"No toolsets found"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:secs.reduce((acc2,s)=>{return acc2.out.push($jsx("box",{height:1,marginTop:acc2.base>0?1:0,children:$jsxs("text",{fg:theme.textMuted,children:["\u2500 ",KIND_LABEL[s.kind]," (",s.items.length,") "]})},`\xA7${s.kind}`)),s.items.forEach((t2,j2)=>{let i=acc2.base+j2;acc2.out.push($jsx(Row2,{id:follow.id(i),ts:t2,selected:i===sel,onSelect:()=>setSel(i),onHover:()=>setSel(i)},t2.name))}),acc2.base+=s.items.length,acc2},{base:0,out:[]}).out},"list")]}),ts?$jsx(DetailPanel3,{ts}):null]}),$jsx(HintBar,{pairs:[["\u2191\u2193","nav"],[keys.print("list.toggle"),"toggle"],[keys.print("list.refresh"),"refresh"]]})]})});var import_react92=__toESM(require_react_production(),1);var mask=(val)=>"\u2022".repeat(Math.min(val.length,12)),VarRow=import_react92.memo((props)=>{let theme=useTheme().theme,set2=props.value!==void 0,bg2=props.selected?theme.backgroundElement:void 0;return $jsxs("box",{id:props.id,flexDirection:"row",height:1,backgroundColor:bg2,onMouseDown:props.onClick,onMouseMove:props.onHover,children:[$jsx(Col,{w:2,fg:props.selected?theme.primary:theme.text,children:props.selected?"\u25B8 ":" "}),$jsx(Col,{w:28,fg:props.selected?theme.accent:theme.text,children:props.name}),$jsx(Col,{w:8,fg:set2?theme.success:theme.textMuted,children:set2?" SET ":"UNSET"}),$jsx(Col,{grow:!0,min:4,fg:props.shown?theme.text:theme.textMuted,children:set2?props.shown?props.value:mask(props.value):"\u2014"})]})}),Env=import_react92.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),vars=useHome("env")??{},[sel,setSel]=import_react92.useState(0),[reveal,setReveal]=import_react92.useState(new Set),[collapsed,setCollapsed]=import_react92.useState({}),[searching,setSearching]=import_react92.useState(!1),[query,setQuery]=import_react92.useState(""),known=new Set(ENV_CATALOG.flatMap((g)=>g.keys)),extra=Object.keys(vars).filter((k2)=>!known.has(k2)).sort(),rows3=(extra.length>0?[...ENV_CATALOG,{category:"Other",keys:extra}]:ENV_CATALOG).flatMap((g)=>{let keys2=searching&&query.trim()?g.keys.filter((k2)=>k2.toLowerCase().includes(query.toLowerCase())):g.keys;if(keys2.length===0)return[];let hide=collapsed[g.category]??!1,header={type:"header",category:g.category,collapsed:hide};if(hide)return[header];return[header,...keys2.map((key3)=>({type:"var",key:key3,value:vars[key3]}))]}),count3=rows3.length,cur=rows3[sel],setKeys=rows3.flatMap((r)=>r.type==="var"&&r.value!==void 0?[r.key]:[]),follow=useFollow("env"),edit=import_react92.useCallback(async(key3,initial)=>{let val=await openTextPrompt(dialog,{title:`Edit ${key3}`,label:"Value",initial});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} saved`})},[dialog,toast]),add2=import_react92.useCallback(async()=>{let key3=await openTextPrompt(dialog,{title:"New Variable",label:"Name (e.g. FOO_API_KEY)"});if(!key3)return;let val=await openTextPrompt(dialog,{title:`Set ${key3}`,label:"Value"});if(val==null)return;await writeEnvVar(key3,val),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} added`})},[dialog,toast]),del=import_react92.useCallback(async(key3)=>{if(!await openConfirm(dialog,{title:"Delete Variable",body:`Remove ${key3} from .env?`,yes:"delete",danger:!0}))return;await removeEnvVar(key3),home2.invalidate("env"),toast.show({variant:"success",message:`${key3} removed`})},[dialog,toast]),revealAll=import_react92.useCallback(()=>setReveal((s)=>s.size===setKeys.length&&setKeys.length>0?new Set:new Set(setKeys)),[setKeys]),activateAt=import_react92.useCallback((i)=>{let r=rows3[i];if(r?.type==="header")return setCollapsed((p)=>({...p,[r.category]:!p[r.category]}));if(r?.type==="var"){if(r.value!==void 0&&!reveal.has(r.key))return setReveal((s)=>new Set(s).add(r.key));return void edit(r.key,r.value??"")}},[rows3,reveal,edit]),activate=import_react92.useCallback(()=>activateAt(sel),[activateAt,sel]),rowClick=import_react92.useCallback((i)=>{setSel(i),activateAt(i)},[activateAt]),keys=useKeys();return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(searching){if(key3.name==="escape"){setSearching(!1),setQuery(""),setSel(0);return}if(key3.name==="backspace"){setQuery((q4)=>q4.slice(0,-1)),setSel(0);return}if(key3.name==="up")return setSel((p)=>Math.max(0,p-1));if(key3.name==="down")return setSel((p)=>Math.min(count3-1,p+1));if(key3.name==="return")return setSearching(!1),activate();if(key3.raw&&key3.raw.length===1&&key3.raw>=" "){setQuery((q4)=>q4+key3.raw),setSel(0);return}return}handleListKey(keys,key3,{count:count3,setSel,...follow.opts,onActivate:activate,onToggle:revealAll,onNew:add2,onDelete:()=>{if(cur?.type==="var"&&cur.value!==void 0)del(cur.key)},onSearch:()=>{setSearching(!0),setQuery(""),setSel(0)},onRefresh:()=>{home2.invalidate("env"),toast.show({variant:"info",message:"Reloaded",duration:1000})}})}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs(TabShell,{title:searching?"Env (searching)":"Env / API Keys",children:[searching?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:"/ "}),$jsx("span",{fg:theme.text,children:query}),$jsx("span",{fg:theme.accent,children:"\u2588"})]})}):null,$jsxs(Hdr,{children:[$jsx(Col,{w:2,fg:theme.textMuted,children:""}),$jsx(Col,{w:28,fg:theme.textMuted,bold:!0,children:"Name"}),$jsx(Col,{w:8,fg:theme.textMuted,bold:!0,children:"Status"}),$jsx(Col,{grow:!0,min:4,fg:theme.textMuted,bold:!0,children:"Value"})]}),$jsx("box",{height:1}),count3===0?$jsx("box",{flexGrow:1,padding:2,children:$jsx("text",{fg:theme.textMuted,children:searching?"No matching variables":"No variables configured"})},"empty"):$jsx("scrollbox",{ref:follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((row3,i)=>row3.type==="header"?$jsx("box",{id:follow.id(i),marginTop:i>0?1:0,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>rowClick(i),children:$jsx("text",{fg:theme.info,children:$jsx("strong",{children:`${row3.collapsed?"\u25B8":"\u25BE"} ${row3.category}`})})},`h-${row3.category}`):$jsx(VarRow,{id:follow.id(i),name:row3.key,value:row3.value,shown:reveal.has(row3.key),selected:i===sel,onHover:()=>setSel(i),onClick:()=>rowClick(i)},row3.key))})},"list")]}),$jsx(HintBar,{pairs:searching?[["\u2191\u2193","move"],["Enter","reveal/edit"],["Esc","cancel"]]:[["\u2191\u2193","move"],[keys.print("list.activate"),"reveal/edit"],[keys.print("list.toggle"),"show-all"],[keys.print("list.new"),"new"],[keys.print("list.delete"),"delete"],[keys.print("list.search"),"search"],[keys.print("list.refresh"),"reload"]]})]})});var import_react94=__toESM(require_react_production(),1);function usageColor(pct,theme){if(pct>=95)return theme.error;if(pct>=80)return theme.warning;return theme.success}function bar2(pct,w2){let filled=Math.round(pct/100*w2);return"\u2588".repeat(filled)+"\u2591".repeat(w2-filled)}var DESC={builtin:"File-based \xA7-delimited entries (MEMORY.md + USER.md). Always active.",mem0:"Server-side LLM fact extraction with semantic search and reranking.",honcho:"AI-native cross-session user modeling with dialectic Q&A.",hindsight:"Knowledge graph with entity resolution and multi-strategy retrieval.",holographic:"Local SQLite fact store with FTS5, trust scoring, HRR retrieval.",openviking:"Session-managed memory with tiered retrieval.",retaindb:"Cloud memory API with hybrid search and 7 memory types.",byterover:"Persistent knowledge tree via brv CLI.",supermemory:"Semantic long-term memory with profile recall and session ingest."},Memory=import_react94.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),gw=useGateway(),[sel,setSel]=import_react94.useState(0),config=useHome("config"),memory=useHome("memory"),userProfile=useHome("userProfile"),providers=useHome("memoryProviders")??[],activity=useHome("memoryActivity")??[],cfg=config?.memory,active=cfg?.provider||"",cur=providers[sel],on=!!cur&&(cur.name==="builtin"||cur.name===active),toggle=async()=>{if(!cur||cur.name==="builtin")return;let isOn=cur.name===active;if(!await openConfirm(dialog,{title:isOn?"Deactivate memory provider?":"Activate memory provider?",body:isOn?`Clear '${cur.name}' as the active provider (revert to built-in only).`:`Set '${cur.name}' as the active provider. Ensure required env vars are set (Env tab).`,yes:isOn?"deactivate":"activate"}))return;let{writeConfig:writeConfig2}=await Promise.resolve().then(() => (init_lane(),exports_lane)),r=await writeConfig2(gw,[{key:"memory.provider",to:isOn?"":cur.name}]);if(r.failed.length)return toast.show({variant:"error",message:r.failed[0].err});home2.invalidate("config"),home2.invalidate("memoryProviders"),toast.show({variant:"success",message:isOn?"Deactivated":`Activated ${cur.name} \u2014 new sessions pick this up`})},keys=useListKeys({active:()=>!!props.focused&&!dialog.open(),count:providers.length,setSel,onToggle:toggle,onRefresh:()=>{home2.invalidate("memoryProviders"),home2.invalidate("memoryActivity"),toast.show({variant:"info",message:"Reloaded",duration:1000})}}),feed=!cur?[]:cur.name==="builtin"?activity:activity.filter((a)=>a.provider===cur.name);return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:"Memory Providers",grow:1,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:providers.map((p,i)=>{let pOn=p.name==="builtin"||p.name===active,has=Object.keys(p.config).length>0,dot=pOn?"\u25CF":has?"\u25D0":"\u25CB",fg2=pOn?theme.success:has?theme.warning:theme.textMuted,tag=pOn?"active":has?"configured":"";return $jsxs("box",{flexDirection:"column",marginBottom:1,backgroundColor:i===sel?theme.backgroundElement:void 0,onMouseDown:()=>setSel(i),onMouseMove:()=>setSel(i),children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:fg2,children:[dot," "]}),$jsx("span",{fg:i===sel?theme.accent:theme.text,children:p.name}),tag?$jsxs("span",{fg:fg2,children:[" (",tag,")"]}):null]})}),$jsx("box",{height:1,overflow:"hidden",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,children:DESC[p.name]||"\u2014"})})]},p.name)})})}),$jsx(TabShell,{title:cur?.name??"Provider",grow:2,children:cur?$jsx(ProviderDetail,{provider:cur,active,cfg,memory,userProfile,feed}):$jsx("text",{fg:theme.textMuted,children:"Select a provider"})})]}),$jsx(HintBar,{pairs:[["\u2191\u2193","select"],[keys.print("list.toggle"),"activate"]],suffix:on?"\u25CF active":"\u25CB inactive"})]})}),ProviderDetail=import_react94.memo((props)=>{let theme=useTheme().theme,p=props.provider,on=p.name==="builtin"||p.name===props.active;return $jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsxs("box",{flexDirection:"column",children:[$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",fg:theme.textMuted,children:DESC[p.name]||"Memory provider"})}),$jsx("box",{height:1}),p.name==="builtin"?$jsxs("box",{flexDirection:"column",children:[props.cfg?$jsxs($Fragment,{children:[$jsx(KVBlock,{rows:[["Notes",props.cfg.memory_enabled?"enabled":"disabled",props.cfg.memory_enabled?theme.success:theme.error],["Profile",props.cfg.user_profile_enabled?"enabled":"disabled",props.cfg.user_profile_enabled?theme.success:theme.error]]}),$jsx("box",{height:1})]}):null,$jsx(CapacityBar,{title:"Notes (MEMORY.md)",info:props.memory??null}),$jsx("box",{height:1}),$jsx(CapacityBar,{title:"Profile (USER.md)",info:props.userProfile??null})]}):null,p.name!=="builtin"&&on&&props.cfg?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Agent Settings"})})}),$jsx(KVBlock,{rows:[["Nudge",`every ${props.cfg.nudge_interval} turns`],["Flush",`after ${props.cfg.flush_min_turns} turns`]]}),$jsx("box",{height:1})]}):null,Object.keys(p.config).length>0?$jsxs($Fragment,{children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.accent,children:$jsx("strong",{children:"Local Configuration"})})}),$jsx(KVBlock,{rows:Object.entries(p.config).map(([k2,v2])=>[k2,String(v2)])})]}):p.name!=="builtin"?$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"No local config found. Run `hermes memory setup` to configure."})}):null,$jsx(ActivityFeed,{items:props.feed,own:p.name})]})})}),OP_GLYPH={write:"+",read:"?"},ActivityFeed=import_react94.memo((props)=>{let theme=useTheme().theme,all=props.own==="builtin",nW=props.items.filter((a)=>a.op==="write").length;return $jsxs("box",{flexDirection:"column",marginTop:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.accent,children:$jsx("strong",{children:"Recent Activity"})}),props.items.length?$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",nW," writes, ",props.items.length-nW," reads"]}):null]})}),props.items.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No memory-tool calls in the last ~2000 messages"})}):null,props.items.map((a,i)=>$jsx("box",{height:1,flexDirection:"row",overflow:"hidden",children:$jsxs("text",{children:[$jsxs("span",{fg:a.op==="write"?theme.success:theme.textMuted,children:[OP_GLYPH[a.op]," "]}),$jsx("span",{fg:theme.textMuted,children:ago(a.ts).padEnd(8)}),all&&a.provider!=="builtin"?$jsxs("span",{fg:theme.primary,children:[a.provider,"\xB7"]}):null,$jsx("span",{fg:theme.text,children:a.verb}),$jsxs("span",{fg:theme.textMuted,children:[" ",a.summary]})]})},i))]})}),CapacityBar=import_react94.memo((props)=>{let theme=useTheme().theme;if(!props.info)return $jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.title,": unavailable"]})});let color=usageColor(props.info.usagePercent,theme);return $jsxs("box",{flexDirection:"column",children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:props.title}),$jsxs("span",{fg:theme.textMuted,children:[" \xB7 ",props.info.entryCount," entries"]})]})}),$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:color,children:bar2(props.info.usagePercent,20)}),$jsxs("span",{fg:theme.textMuted,children:[" ",props.info.charCount,"/",props.info.charLimit," (",props.info.usagePercent,"%)"]})]})})]})});var ConfigGroup=import_react95.memo((props)=>{let labels=SUB_TABS[CONFIG_TAB];import_react95.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,flexDirection:"column",children:[$jsx(Pane3,{visible:props.sub===0,children:$jsx(Config,{focused:!!props.focused&&props.sub===0})}),$jsx(Pane3,{visible:props.sub===1,children:$jsx(Skills,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane3,{visible:props.sub===2,children:$jsx(Toolsets,{focused:!!props.focused&&props.sub===2})}),$jsx(Pane3,{visible:props.sub===3,children:$jsx(Env,{focused:!!props.focused&&props.sub===3})}),$jsx(Pane3,{visible:props.sub===4,children:$jsx(Memory,{focused:!!props.focused&&props.sub===4})})]})]})}),Pane3=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react111=__toESM(require_react_production(),1);var import_react104=__toESM(require_react_production(),1);import{existsSync as existsSync20}from"fs";import{basename as basename13}from"path";var import_react96=__toESM(require_react_production(),1);var PathPrompt=(props)=>{let theme=useTheme().theme,[value,setValue]=import_react96.useState(props.initial??""),[items,setItems]=import_react96.useState([]),seq=import_react96.useRef(0),ok=(it)=>it.meta==="dir"||!props.filter||props.filter.test(it.text);return import_react96.useEffect(()=>{if(!value.trim()){setItems([]);return}let me2=++seq.current,t2=setTimeout(()=>{props.gw.request("complete.path",{word:value}).then((r)=>{if(seq.current===me2)setItems((r.items??[]).filter(ok).slice(0,5))}).catch(()=>{if(seq.current===me2)setItems([])})},120);return()=>clearTimeout(t2)},[value,props.gw]),useKeyboard((key3)=>{if(key3.name!=="tab")return;key3.preventDefault();let hit=items[0];if(hit)setValue(hit.text)}),$jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),$jsx("box",{height:1}),props.label?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.label})}):null,$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.accent,children:"\u2503 "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value,onInput:setValue,onSubmit:()=>{let v2=value.trim();if(v2)props.onSubmit(v2)},focused:!0,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]}),$jsx("box",{height:1}),items.length>0?items.map((it)=>$jsxs("box",{height:1,flexDirection:"row",overflow:"hidden",children:[$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:it.text})}),it.meta?$jsx("box",{flexShrink:0,height:1,children:$jsx("text",{fg:theme.textMuted,children:` ${it.meta}`})}):null]},it.text)):null,items.length>0?$jsx("box",{height:1}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:value.trim()?`Tab complete \xB7 Enter confirm \xB7 Esc cancel${items.length>0?` \xB7 ${items.length} match${items.length===1?"":"es"}`:""}`:"Type a path \xB7 Esc cancel"})})]})};function openPathPrompt(dialog,gw,opts){return new Promise((resolve4)=>{dialog.replace($jsx(PathPrompt,{title:opts.title,label:opts.label,initial:opts.initial,filter:opts.filter,gw,onSubmit:(v2)=>{resolve4(v2),dialog.clear()}}),()=>resolve4(null))})}var import_react98=__toESM(require_react_production(),1);var BASE=`
|
|
4148
|
+
high contrast, light subject on dark, black background`,BINDS=[{name:"return",action:"submit"},{name:"return",shift:!0,action:"newline"}],Generate=(props)=>{let theme=useTheme().theme,ta=import_react98.useRef(null),[prompt,setPrompt]=import_react98.useState(props.lastPrompt??BASE),[useSeed,setUseSeed]=import_react98.useState(!!props.seed),[secs,setSecs]=import_react98.useState(2),[busy,setBusy]=import_react98.useState(!1),[err,setErr]=import_react98.useState(null),[field,setField]=import_react98.useState("prompt");import_react98.useEffect(()=>{ta.current?.setCursor(0,0)},[]);let fields=props.kind==="video"?props.seed?["prompt","seed","seconds","submit"]:["prompt","seconds","submit"]:props.seed?["prompt","seed","submit"]:["prompt","submit"],advance=()=>setField((f)=>fields[(fields.indexOf(f)+1)%fields.length]),submit2=()=>{let p=prompt.trim(),bare=!props.lastPrompt&&p===BASE.trim();if(!p||bare||busy){if(bare)setErr("describe the subject on line 1");return}setBusy(!0),setErr(null),props.run(props.kind,p,{seed:props.seed&&useSeed?props.seed:void 0,seconds:props.kind==="video"?secs:void 0,aspect:props.kind==="video"?"1:1":"square"}).then((r)=>{if("err"in r){setErr(r.err),setBusy(!1);return}props.onDone(r.path,p)})};useKeyboard((key3)=>{if(busy)return;if(key3.name==="tab"){key3.preventDefault();let i=fields.indexOf(field),next2=fields[(i+(key3.shift?fields.length-1:1))%fields.length];setField(next2);return}if(field==="prompt")return;if(key3.name==="return")return field==="submit"?submit2():advance();if(field==="seed"&&(key3.name==="space"||key3.name==="left"||key3.name==="right")){setUseSeed((v2)=>!v2);return}if(field==="seconds"){if(key3.name==="left")return setSecs((v2)=>Math.max(1,v2-1));if(key3.name==="right")return setSecs((v2)=>Math.min(4,v2+1))}if(field==="submit"&&key3.name==="space")submit2()});let lbl=(id,text3)=>$jsx("box",{width:12,flexShrink:0,children:$jsxs("text",{fg:field===id?theme.accent:theme.textMuted,children:[field===id?"\u25B8 ":" ",text3]})});return $jsxs("box",{flexDirection:"column",width:72,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:`Generate ${props.kind} \u2014 ${props.state}`})})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",children:[lbl("prompt","Prompt"),$jsx("box",{flexGrow:1,minWidth:0,children:$jsx("textarea",{ref:ta,initialValue:prompt,keyBindings:BINDS,onSubmit:advance,onContentChange:()=>{if(ta.current)setPrompt(ta.current.plainText)},focused:field==="prompt",placeholder:props.kind==="image"?"describe the image\u2026":"describe the motion\u2026",textColor:theme.text,placeholderColor:theme.textMuted,backgroundColor:field==="prompt"?theme.backgroundElement:void 0,focusedBackgroundColor:theme.backgroundElement,minHeight:4,maxHeight:6})})]}),props.seed?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seed","Seed"),$jsx("box",{flexGrow:1,minWidth:0,height:1,children:$jsx("text",{fg:field==="seed"?theme.text:theme.textMuted,children:useSeed?"\u25CF base.png":"\u25CB none"})})]}):null,props.kind==="video"?$jsxs("box",{height:1,flexDirection:"row",marginTop:1,children:[lbl("seconds","Seconds"),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:1,max:4,value:secs,foregroundColor:field==="seconds"?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>setSecs(Math.round(v2))})}),$jsx("box",{width:6,height:1,children:$jsx("text",{fg:field==="seconds"?theme.text:theme.textMuted,children:` ${secs}s`})})]}):null,$jsxs("box",{marginTop:1,flexDirection:"row",children:[lbl("submit",""),$jsx("box",{flexGrow:1,minWidth:0,children:busy?$jsx("box",{height:1,children:$jsx(Spinner,{color:theme.accent,label:"generating\u2026"})}):err?$jsx("text",{fg:theme.warning,wrapMode:"word",children:err}):$jsx("box",{height:1,children:$jsx("text",{fg:field==="submit"?theme.accent:theme.textMuted,children:"[Enter] generate"})})})]}),$jsx("box",{height:1,marginTop:1,children:$jsx("text",{fg:theme.textMuted,children:"Enter next \xB7 Shift+Enter newline \xB7 Tab field \xB7 Esc cancel"})})]})};function openGenerate(dialog,run,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Generate,{...opts,run,onDone:(p,txt)=>{resolve4(p?{path:p,prompt:txt}:null),dialog.clear()}}),()=>resolve4(null))})}var import_react100=__toESM(require_react_production(),1);import{copyFileSync as copyFileSync3,existsSync as existsSync18,mkdirSync as mkdirSync5,readFileSync as readFileSync11,rmSync as rmSync4,writeFileSync as writeFileSync6}from"fs";import{createHash as createHash4}from"crypto";import{isIP}from"net";import{basename as basename12,dirname as dirname12,join as join15}from"path";var exports_eikon={};__export(exports_eikon,{writeStudio:()=>writeStudio,useInstalled:()=>useInstalled,update:()=>update,studioFile:()=>studioFile,sourceStatus:()=>sourceStatus,sourceStamp:()=>sourceStamp,sourceName:()=>sourceName,sourceFetchUrl:()=>sourceFetchUrl,sourceExt:()=>sourceExt,sourceDir:()=>sourceDir,save:()=>save2,revision:()=>revision,remove:()=>remove2,register:()=>register,readStudio:()=>readStudio,raw:()=>raw,rasterizers:()=>rasterizers,rasterizer:()=>rasterizer,probe:()=>probe,previewPackage:()=>previewPackage,pick:()=>pick,peekSource:()=>peekSource,parseEikonFile:()=>parseEikonFile,parseEikon:()=>parseEikon,onRevision:()=>onRevision,onRegistry:()=>onRegistry,notifyRevision:()=>notifyRevision,localSources:()=>localSources,loadCatalog:()=>loadCatalog2,list:()=>list2,lifecycle:()=>lifecycle,installPackage:()=>installPackage,inspectSource:()=>inspectSource,header:()=>header,hasLocalSource:()=>hasLocalSource,findSource:()=>findSource,file:()=>file,fetchSource:()=>fetchSource,ensure:()=>ensure,eikon:()=>exports_eikon,downloadSource:()=>downloadSource,dir:()=>dir,baked:()=>baked,attachSources:()=>attachSources,adopt:()=>adopt,adaptPackage:()=>adaptPackage});import{existsSync as existsSync17,mkdirSync as mkdirSync4,readdirSync as readdirSync6,copyFileSync as copyFileSync2,readFileSync as readFileSync10,writeFileSync as writeFileSync5,rmSync as rmSync3,statSync as statSync6,renameSync as renameSync3}from"fs";import{createHash as createHash3}from"crypto";import{join as join14,extname as extname3,basename as basename11,dirname as dirname11}from"path";import{existsSync as existsSync16,readFileSync as readFileSync9}from"fs";import{join as join13,dirname as dirname10}from"path";var locate2=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join13(d2,"assets/eikons");if(existsSync16(p))return p;let up=dirname10(d2);if(up===d2)break;d2=up}return join13(import.meta.dir,"../../../assets/eikons")},BUNDLED_EIKON_DIR=locate2(),packageEntrypoint=(dir)=>{let manifest2=join13(dir,"manifest.json");if(!existsSync16(manifest2))return;try{let entrypoints=JSON.parse(readFileSync9(manifest2,"utf8")).entrypoints,value=entrypoints&&typeof entrypoints==="object"&&!Array.isArray(entrypoints)?entrypoints.default:void 0,path7=typeof value==="string"?join13(dir,value):void 0;return path7&&existsSync16(path7)?path7:void 0}catch{return}};function bundledEikonPath(name){if(!name)return;let id=name==="default"?"nous":name,dir=join13(BUNDLED_EIKON_DIR,id),entry2=packageEntrypoint(dir);if(entry2)return entry2;for(let p of[join13(dir,`${id}.eikon`),join13(BUNDLED_EIKON_DIR,`${id}.eikon`)])if(existsSync16(p))return p;return}import{deflateSync}from"zlib";import{spawnSync as spawnSync2}from"child_process";import{statSync as statSync5}from"fs";var W2=48,H=24,FPS0=16,MAXF=256,S0={zoom:1,ox:0.5,oy:0.5},T0={contrast:1,invert:!0,flip:"none"},defaults=(r)=>Object.fromEntries(Object.entries(r.knobs).map(([k2,d2])=>[k2,d2.default])),caps2={chafa:chafaBin(),ffmpeg:spawnSync2("ffmpeg",["-version"],{stdio:"ignore"}).status===0,ffprobe:spawnSync2("ffprobe",["-version"],{stdio:"ignore"}).status===0};function probe(path7){if(!caps2.ffprobe)return null;let r=spawnSync2("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",path7],{encoding:"utf8"});if(r.status!==0)return null;let m2=r.stdout.trim().match(/^(\d+),(\d+)/);return m2?{w:+m2[1],h:+m2[2]}:null}var clamp=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),SCALE=384,PLANE=SCALE*SCALE,VID=/\.(mp4|webm|mov|mkv|m4v|gif)$/i,clips=new Map,CLIP_CAP=8;function decode2(src3,fps=FPS0){let full=resolveImage(src3);if(!full)return Promise.resolve(`not found: ${src3}`);let mt=statSync5(full,{throwIfNoEntry:!1})?.mtimeMs??0,key3=`${full}:${mt}:${fps}`,got=clips.get(key3);if(got)return clips.delete(key3),clips.set(key3,got),got;if(!caps2.ffmpeg)return Promise.resolve("ffmpeg not installed");let video=VID.test(full),vf=[...video?[`fps=${fps}`]:[],`scale=${SCALE}:${SCALE}:force_original_aspect_ratio=increase`,`crop=${SCALE}:${SCALE}`].join(","),p=(async()=>{let ff=Bun.spawn(["ffmpeg","-hide_banner","-loglevel","error","-i",full,"-vf",vf,"-frames:v",video?String(MAXF):"1","-f","rawvideo","-pix_fmt","gray","-"],{stdout:"pipe",stderr:"pipe"}),[buf,err]=await Promise.all([new Response(ff.stdout).arrayBuffer().then((b2)=>new Uint8Array(b2)),new Response(ff.stderr).text()]);if(await ff.exited,ff.exitCode!==0)return`ffmpeg: ${err.trim()||"failed"}`;if(buf.length===0||buf.length%PLANE!==0)return`ffmpeg: bad read (${buf.length})`;let n=buf.length/PLANE;return{planes:Array.from({length:n},(_2,i)=>buf.subarray(i*PLANE,(i+1)*PLANE)),fps:video?fps:0,w:SCALE,h:SCALE}})();if(clips.size>=CLIP_CAP)clips.delete(clips.keys().next().value);return clips.set(key3,p),p}var prewarm=(src3,fps=FPS0)=>void decode2(src3,fps);function crop(clip,sp){let side=Math.max(1,Math.round(clip.w*clamp(sp.zoom,0.1,1))),x0=Math.round((clip.w-side)*clamp(sp.ox,0,1)),y0=Math.round((clip.h-side)*clamp(sp.oy,0,1)),n=clip.planes.length,gray=new Uint8Array(side*side*n);for(let f=0;f<n;f++){let pl=clip.planes[f],off=f*side*side;for(let y2=0;y2<side;y2++)gray.set(pl.subarray((y0+y2)*clip.w+x0,(y0+y2)*clip.w+x0+side),off+y2*side)}let enc2;return{gray,w:side,h:side,frames:n,png:()=>enc2??=png(gray,side,side*n)}}function png(gray,w2,h2){let be32=(n)=>new Uint8Array([n>>>24,n>>>16&255,n>>>8&255,n&255]),T2=png_crc,crc=(b2)=>{let c=4294967295;for(let i=0;i<b2.length;i++)c=T2[(c^b2[i])&255]^c>>>8;return~c>>>0},chunk=(tag,data2)=>{let t2=new TextEncoder().encode(tag),body=new Uint8Array(t2.length+data2.length);return body.set(t2),body.set(data2,4),[be32(data2.length),body,be32(crc(body))]},ihdr=new Uint8Array(13);ihdr.set(be32(w2),0),ihdr.set(be32(h2),4),ihdr[8]=8,ihdr[9]=0,ihdr[10]=0,ihdr[11]=0,ihdr[12]=0;let raw=new Uint8Array(h2*(w2+1));for(let y2=0;y2<h2;y2++)raw.set(gray.subarray(y2*w2,(y2+1)*w2),y2*(w2+1)+1);let idat=new Uint8Array(deflateSync(raw,{level:1})),parts2=[new Uint8Array([137,80,78,71,13,10,26,10]),...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))],out=new Uint8Array(parts2.reduce((n,p)=>n+p.length,0)),o=0;for(let p of parts2)out.set(p,o),o+=p.length;return out}var png_crc=(()=>{let t2=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k2=0;k2<8;k2++)c=c&1?3988292384^c>>>1:c>>>1;t2[n]=c>>>0}return t2})(),cache4=new Map,CAP3=256;function put(key3,v2){if(cache4.size>=CAP3)cache4.delete(cache4.keys().next().value);return cache4.set(key3,v2),v2}function hit(key3){let v2=cache4.get(key3);if(!v2)return;return cache4.delete(key3),cache4.set(key3,v2),v2}function resetCache(){cache4.clear(),clips.clear()}var keyOf=(r,src3,sp,tn,fps,k2)=>`${r}|${src3}|${fps}|${sp.zoom.toFixed(3)}:${sp.ox.toFixed(3)}:${sp.oy.toFixed(3)}|${tn.contrast.toFixed(2)}:${+tn.invert}:${tn.flip}|${JSON.stringify(k2)}`;async function cached2(r,src3,sp,tn,fps,k2,signal){let key3=keyOf(r.name,src3,sp,tn,fps,k2),got=hit(key3);if(got)return{frames:got};let cl=await decode2(src3,fps);if(typeof cl==="string")return{err:cl};if(signal?.aborted)return{err:"aborted"};let out=await r.render(tone(crop(cl,sp),tn),k2,signal);if("err"in out)return out;if(signal?.aborted)return{err:"aborted"};return{frames:put(key3,out.frames)}}function pad(rows3){let out=rows3.slice(0,H);while(out.length<H)out.push("");return out.map((l)=>{if(l.includes("\x1B["))return l;let cp=Array.from(l);return cp.length>=W2?cp.slice(0,W2).join(""):l+" ".repeat(W2-cp.length)})}function box(out,n){let rows3=out.replace(/\n$/,"").split(`
|
|
4150
4149
|
`);return Array.from({length:n},(_2,i)=>pad(rows3.slice(i*H,(i+1)*H)))}function thumb(frame,w2=16,h2=8){let fx=W2/w2,fy=H/h2;return Array.from({length:h2},(_2,y2)=>{let row3=Array.from(frame[Math.min(H-1,Math.floor(y2*fy+fy/2))]??""),n=row3.length;return Array.from({length:w2},(_3,x2)=>row3[Math.min(n-1,Math.floor(x2*fx+fx/2))]??" ").join("")})}function tone(win,t2){let{gray:g,w:w2,h:h2,frames:n}=win,sz=w2*h2,flip=t2.flip,con=clamp(t2.contrast,0.25,4);for(let f=0;f<n;f++){let o=f*sz;if(flip==="h"||flip==="hv")for(let y2=0;y2<h2;y2++){let ro=o+y2*w2;for(let x2=0;x2<w2>>1;x2++){let t3=g[ro+x2];g[ro+x2]=g[ro+w2-1-x2],g[ro+w2-1-x2]=t3}}if(flip==="v"||flip==="hv")for(let y2=0;y2<h2>>1;y2++){let a=g.subarray(o+y2*w2,o+(y2+1)*w2),b2=g.subarray(o+(h2-1-y2)*w2,o+(h2-y2)*w2),t3=new Uint8Array(a);a.set(b2),b2.set(t3)}}if(Math.abs(con-1)>0.001)for(let f=0;f<n;f++){let o=f*sz,sum=0;for(let i=0;i<sz;i++)sum+=g[o+i];let m2=sum/sz;for(let i=0;i<sz;i++)g[o+i]=clamp(Math.round((g[o+i]-m2)*con+m2),0,255)}if(t2.invert)for(let i=0;i<g.length;i++)g[i]=255-g[i];return win}var chafa={name:"chafa",knobs:{symbols:{kind:"cycle",options:["braille","block","ascii","sextant","quad","half","wedge"],default:"braille",hint:"Glyph family used to draw pixels. Braille is densest; block is boldest; ascii is most compatible."},fill:{kind:"cycle",options:["none","stipple","ascii","braille"],default:"none",hint:"Secondary glyph set used where the primary leaves gaps."},dither:{kind:"cycle",options:["none","ordered","diffusion","noise"],default:"none",hint:"Adds texture to smooth gradients so mid-tones don't band."}},available:()=>caps2.chafa?!0:"chafa not installed",async render(win,k2,signal){let bin=caps2.chafa;if(!bin)return{err:"chafa not installed"};let fill=String(k2.fill??"none"),args=[`--size=${W2}x${H*win.frames}`,"--format=symbols","--stretch","--colors=none",`--symbols=${String(k2.symbols??"braille")}`,...fill==="none"?[]:[`--fill=${fill}`],`--dither=${String(k2.dither??"none")}`,"--preprocess","off","-"];if(signal?.aborted)return{err:"aborted"};let ch=Bun.spawn([bin,...args],{stdin:win.png(),stdout:"pipe",stderr:"pipe"}),kill=()=>ch.kill();signal?.addEventListener("abort",kill,{once:!0});let[out,cerr]=await Promise.all([new Response(ch.stdout).text(),new Response(ch.stderr).text()]);if(await ch.exited,signal?.removeEventListener("abort",kill),signal?.aborted)return{err:"aborted"};if(ch.exitCode!==0)return{err:`chafa: ${cerr.trim()||"failed"}`};return{frames:box(out,win.frames)}}},DOT=[[1,8],[2,16],[4,32],[64,128]],RAMP=" .:-=+*#%@";function sample(g,w2,h2,fw,fh){let sx=w2/fw,sy=h2/fh;return(gx,gy)=>g[Math.min(h2-1,Math.floor(gy*sy))*w2+Math.min(w2-1,Math.floor(gx*sx))]}function mean(g){let s=0;for(let i=0;i<g.length;i++)s+=g[i];return s/g.length}function braille(g,w2,h2){let at=sample(g,w2,h2,W2*2,H*4),thr=mean(g),rows3=[];for(let y2=0;y2<H;y2++){let row3="";for(let x2=0;x2<W2;x2++){let bits=0;for(let dy=0;dy<4;dy++)for(let dx=0;dx<2;dx++)if(at(x2*2+dx,y2*4+dy)>thr)bits|=DOT[dy][dx];row3+=String.fromCodePoint(10240+bits)}rows3.push(row3)}return rows3}function block(g,w2,h2){let at=sample(g,w2,h2,W2,H),n=RAMP.length-1,rows3=[];for(let y2=0;y2<H;y2++){let row3="";for(let x2=0;x2<W2;x2++)row3+=RAMP[Math.round(at(x2,y2)/255*n)];rows3.push(row3)}return rows3}var native={name:"native",knobs:{symbols:{kind:"cycle",options:["braille","block"],default:"braille",hint:"Glyph family used to draw pixels. Braille is denser; block is bolder."}},available:()=>caps2.ffmpeg?!0:"ffmpeg not installed",async render(win,k2){let fn=k2.symbols==="block"?block:braille,sz=win.w*win.h;return{frames:Array.from({length:win.frames},(_2,i)=>fn(win.gray.subarray(i*sz,(i+1)*sz),win.w,win.h))}}},BUILTIN=[chafa,native];var exports_eikon_knobs={};__export(exports_eikon_knobs,{zoom:()=>zoom,unfork:()=>unfork,toStudio:()=>toStudio,swap:()=>swap,step:()=>step,slug:()=>slug2,setState:()=>setState,setSlider:()=>setSlider,reset:()=>reset2,pan:()=>pan,knobs:()=>exports_eikon_knobs,fresh:()=>fresh,fork:()=>fork,eff:()=>eff,edit:()=>edit,cycle:()=>cycle2,STATES:()=>STATES2});var STATES2=["idle","listening","thinking","speaking","working","error"],clamp2=(x2,lo,hi)=>Math.min(hi,Math.max(lo,x2)),round=(x2,p=3)=>+x2.toFixed(p),wrap=(arr2,cur,d2)=>arr2[(Math.max(0,arr2.indexOf(cur))+d2+arr2.length)%arr2.length];function fresh(name,r,seed){return{name,state:"idle",dims:null,dirty:!1,rasterizer:seed?.rasterizer??r.name,spatial:seed?.spatial??{...S0},tone:{...T0,...seed?.tone},fps:seed?.fps??FPS0,base:seed?.base??defaults(r),per:seed?.per??{},glyph:seed?.glyph??"\u25C6",sources:seed?.sources??{},prompts:seed?.prompts??{}}}var eff=(s,state2)=>s.per[state2]??s.base;function edit(s,fn){let own=s.per[s.state];return own?{...s,per:{...s.per,[s.state]:fn(own)},dirty:!0}:{...s,base:fn(s.base),dirty:!0}}var fork=(s)=>s.per[s.state]?s:{...s,per:{...s.per,[s.state]:{...s.base}},dirty:!0},unfork=(s)=>{if(!s.per[s.state])return s;let{[s.state]:_2,...rest}=s.per;return{...s,per:rest,dirty:!0}},setState=(s,state2)=>({...s,state:state2}),cycle2=(s,d2)=>setState(s,wrap(STATES2,s.state,d2));function step(k2,id,def2,d2){if(def2.kind==="cycle")return{...k2,[id]:wrap(def2.options,String(k2[id]??def2.default),d2)};if(def2.kind==="toggle")return{...k2,[id]:!(k2[id]??def2.default)};let cur=Number(k2[id]??def2.default);return{...k2,[id]:round(clamp2(cur+d2*def2.step,def2.min,def2.max))}}function setSlider(k2,id,def2,v2){if(def2.kind!=="slider")return k2;return{...k2,[id]:round(clamp2(v2,def2.min,def2.max))}}function pan(sp,dx,dy,fine=!1){let s=fine?0.01:0.03;return{zoom:sp.zoom,ox:round(clamp2(sp.ox+dx*s,0,1)),oy:round(clamp2(sp.oy+dy*s,0,1))}}function zoom(sp,d2,fine=!1){let s=fine?0.02:0.05;return{...sp,zoom:round(clamp2(sp.zoom+d2*s,0.1,1))}}function swap(s,r){return{...s,rasterizer:r.name,base:defaults(r),per:{},dirty:!0}}var reset2=(s,r)=>({...s,spatial:{...S0},tone:{...T0},base:defaults(r),per:{},dirty:!0}),slug2=(v2)=>v2.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")||"wip",toStudio=(s)=>({rasterizer:s.rasterizer,spatial:s.spatial,tone:s.tone,fps:s.fps,base:s.base,per:s.per,glyph:s.glyph,sources:s.sources,prompts:s.prompts});var ROOT=()=>hermesPath("eikons"),dir=(name)=>join14(ROOT(),name),file=(name)=>join14(dir(name),`${name}.eikon`),sourceDir=(name)=>join14(dir(name),"source"),studioFile=(name)=>join14(dir(name),"studio.json");function ensure(name){return mkdirSync4(sourceDir(name),{recursive:!0}),{dir:dir(name),file:file(name),source:sourceDir(name)}}function manifest2(name){let p=join14(dir(name),"manifest.json");if(!existsSync17(p))return;try{let raw=JSON.parse(readFileSync10(p,"utf8"));if(raw&&typeof raw==="object")return raw}catch{}return}var LEGACY_SOURCE_URL="source_url",OBJ=(x2)=>!!x2&&typeof x2==="object"&&!Array.isArray(x2);function originObject(man){let o=man?.origin;return OBJ(o)?o:void 0}function origin(man){let src3=originObject(man)?.source;return typeof src3==="string"?src3:void 0}function legacySource(head){let src3=head?.[LEGACY_SOURCE_URL];return typeof src3==="string"?src3:void 0}function display(man){return OBJ(man?.display)?man.display:void 0}function sourceInfo(man,head){let o=originObject(man),src3=typeof o?.source==="string"?o.source:legacySource(head),identity2=o?.identityKey??o?.sourceKey??o?.packageUrl??o?.repo??src3;return{kind:o?.kind??"unknown",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...o?.repo?{repo:o.repo}:{},...o?.selector?{selector:o.selector}:{},...o?.catalogRoot?{catalogRoot:o.catalogRoot}:{},...o?.sha?{sha:o.sha}:{},...o?.packageUrl?{packageUrl:o.packageUrl}:{}}}function displayTitle(man){let disp=display(man);return typeof disp?.title==="string"?disp.title:typeof man?.title==="string"?man.title:void 0}function displayAuthor(man){let disp=display(man);return typeof disp?.author==="string"?disp.author:typeof man?.author==="string"?man.author:void 0}function sourceLabel(src3){let id=src3.repo??src3.identity??src3.origin??src3.packageUrl;if(!id)return src3.kind;if(src3.sha)return`${src3.kind} ${id}@${src3.sha.slice(0,12)}`;return`${src3.kind} ${id}`}function inspectResolved(src3,r,stat2){let{manifest:man,origin:o}=r,info2={kind:o.kind??"unknown",...o.identityKey||o.sourceKey||o.packageUrl||o.repo||o.source?{identity:o.identityKey??o.sourceKey??o.packageUrl??o.repo??o.source}:{},...o.source?{origin:o.source}:{},...o.repo?{repo:o.repo}:{},...o.selector?{selector:o.selector}:{},...o.catalogRoot?{catalogRoot:o.catalogRoot}:{},...o.sha?{sha:o.sha}:{},...o.packageUrl?{packageUrl:o.packageUrl}:{}},compatibility=OBJ(man.compatibility)?man.compatibility:void 0,poster2=typeof man.poster==="string"?man.poster:void 0,preview2=typeof man.preview==="string"?man.preview:void 0,out={name:r.name,...displayTitle(man)?{title:displayTitle(man)}:{},...displayAuthor(man)?{author:displayAuthor(man)}:{},...typeof man.version==="string"?{version:man.version}:{},source:info2,trust:r.trust.state,active:get2("eikon")===r.name,removable:!1,updateable:!0,updateAvailable:!1,dirty:!1,...poster2?{poster:poster2}:{},...preview2?{preview:preview2}:{},...compatibility?{compatibility}:{},installed:existsSync17(file(r.name)),sourceLabel:sourceLabel(info2),previewAvailable:Boolean(preview2||man.entrypoints?.default),posterAvailable:Boolean(poster2),...stat2?{n:stat2.n,bytes:stat2.bytes}:{},...r.trust.reason?{reason:r.trust.reason}:{}};if(!out.source.origin)out.source.origin=src3;return out}function changed(name){try{return dirty(dir(name))}catch{return!1}}function lifecycle(name,opts={}){let man=manifest2(name),head=header(file(name)),src3=sourceInfo(man,head),title=displayTitle(man),author=displayAuthor(man),version=typeof man?.version==="string"?man.version:void 0,compatibility=OBJ(man?.compatibility)?man.compatibility:void 0,installedAt=originObject(man)?.at,hasOrigin=Boolean(src3.origin??src3.packageUrl),isDirty=opts.dirty!==!1&&existsSync17(dir(name))?changed(name):!1;return{name,...title?{title}:{},...author?{author}:{},...version?{version}:{},source:src3,trust:originObject(man)?.trust??(src3.origin?"unverified":"unknown"),active:get2("eikon")===name,removable:existsSync17(file(name)),updateable:hasOrigin,updateAvailable:!1,dirty:isDirty,...typeof man?.poster==="string"?{poster:man.poster}:{},...typeof man?.preview==="string"?{preview:man.preview}:{},...compatibility?{compatibility}:{},...installedAt?{installedAt}:{}}}function list2(){let root2=ROOT();if(!existsSync17(root2))return[];return readdirSync6(root2,{withFileTypes:!0}).filter((e)=>e.isDirectory()&&existsSync17(join14(root2,e.name,`${e.name}.eikon`))).map((e)=>{let name=e.name;normalizeStoredSources(name);let man=manifest2(name),path7=join14(root2,name,`${name}.eikon`);return{name,file:path7,source:join14(root2,name,"source"),hasSource:hasLocalSource(name),sourceUrl:sourceUrl(man,header(path7)),manifest:man,lifecycle:lifecycle(name,{dirty:!1})}})}function raw(){let root2=ROOT();if(!existsSync17(root2))return[];return readdirSync6(root2,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>e.name)}var IMG=/\.(png|jpe?g|webp|gif|bmp)$/i,VID2=/\.(mp4|webm|mov|mkv)$/i,MEDIA_EXT={"image/png":".png","image/jpeg":".jpg","image/jpg":".jpg","image/webp":".webp","image/gif":".gif","image/bmp":".bmp","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","video/x-matroska":".mkv"};function slot(role){return role==="base"||STATES2.includes(role)}function sourceExt(man,rel2){let ext=extname3(rel2).toLowerCase();if(ext)return ext;let type=man?.files?.find((f)=>f.path===rel2)?.mediaType?.split(";")[0]?.trim().toLowerCase();return type?MEDIA_EXT[type]??"":""}function sourceName(man,role,rel2){return`${role}${sourceExt(man,rel2)}`}function sourceRefs(man){if(!man)return new Map;try{return new Map(entries(man).filter(([role])=>slot(String(role))).map(([role,rel2])=>[String(role),rel2]))}catch{return new Map}}function normalizeSources(name,sources){let man=manifest2(name),refs=sourceRefs(man),root2=sourceDir(name);return Object.fromEntries(Object.entries(sources).map(([role,fname])=>{if(!fname)return[role,fname];let rel2=refs.get(role),next2=rel2?sourceName(man,role,rel2):fname;if(next2===fname)return[role,fname];let from2=join14(root2,fname),to=join14(root2,next2);if(existsSync17(from2)&&!existsSync17(to))renameSync3(from2,to);return[role,existsSync17(to)?next2:fname]}))}function sameSources(a,b2){return JSON.stringify(a)===JSON.stringify(b2)}function normalizeStudioSources(name,s){let prev=s.sources??{},sources=normalizeSources(name,prev);if(sameSources(prev,sources))return s;let next2={...s,sources};return writeFileSync5(studioFile(name),JSON.stringify(next2,null,2)+`
|
|
4151
4150
|
`,"utf8"),next2}function normalizeStoredSources(name){try{readStudio(name)}catch{}}function fileOk(name){return IMG.test(name)||VID2.test(name)}function roleOf(name){let stem=basename11(name,extname3(name)).toLowerCase();if(stem==="base")return"base";return STATES2.includes(stem)?stem:void 0}function sourcePath(name,value){return value.includes("/")?value:join14(sourceDir(name),value)}function storedName(value){return value.includes("/")?basename11(value):value}function sourceFiles(name){let src3=sourceDir(name);if(!existsSync17(src3))return[];return readdirSync6(src3).filter(fileOk)}function byRole(files,role){return files.find((f)=>roleOf(f)===role)}function roles(state2){if(!state2)return["base","idle"];return state2==="idle"?["idle","base"]:[state2,"base","idle"]}function entryRole(value,path7){if(value==="source.base")return"base";if(value?.startsWith("source.")){let role=value.slice(7);if(role==="base")return"base";if(STATES2.includes(role))return role}return roleOf(path7)??"base"}function sourceEntries(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([role,path7])=>[role,path7]);if(xs.length)return xs}catch(err){if(strict)throw err}return(Array.isArray(man.files)?man.files:[]).flatMap((file2)=>{if(typeof file2==="string")return[[entryRole(void 0,file2)??"base",file2]];if(!OBJ(file2)||typeof file2.path!=="string"||!String(file2.role??"").startsWith("source"))return[];let role=entryRole(typeof file2.role==="string"?file2.role:void 0,file2.path);return role?[[role,file2.path]]:[]})}function sourceUrl(man,head){let src3=sourceInfo(man,head);return src3.packageUrl??src3.origin}function sourceFetchUrl(name){return sourceUrl(manifest2(name),header(file(name)))}function sourceStatus(name,state2,opts={}){let seed=opts.sources??readStudio(name)?.sources,files=sourceFiles(name),removed=new Set(Object.entries(seed??{}).flatMap(([role,value])=>value===null?[role]:[])),visible2=files.filter((f)=>{let role=roleOf(f);return!role||!removed.has(role)}),hit2=(role)=>{if(removed.has(role))return;let value=seed?.[role];if(typeof value==="string"&&value){let path7=sourcePath(name,value);if(existsSync17(path7)&&fileOk(path7))return{path:path7,file:storedName(value),role,origin:opts.sources?"draft":"studio"}}let file2=byRole(visible2,role);return file2?{path:join14(sourceDir(name),file2),file:file2,role,origin:"discovered"}:void 0},found=roles(state2).map(hit2).find(Boolean),first=removed.size?void 0:visible2.find((f)=>IMG.test(f))??visible2.find((f)=>VID2.test(f)),src3=found??(first?{path:join14(sourceDir(name),first),file:first,role:roleOf(first),origin:"fallback"}:void 0),st=state2??"idle",own=Boolean(src3?.role&&(src3.role===st||st==="idle"&&src3.role==="base")),man=manifest2(name),pack=baked(name),head=header(file(name))??(pack?header(pack):void 0),url2=sourceUrl(man,head),downloadable=!src3&&Boolean(url2),size=src3?.path?(()=>{try{return statSync6(src3.path).size}catch{return}})():void 0;return{name,state:st,kind:src3?"local":downloadable?"downloadable":pack?"baked":"missing",...src3?.path?{path:src3.path}:{},...src3?.file?{file:src3.file}:{},...size!==void 0?{size}:{},...src3?.role?{role:src3.role}:{},...src3?.origin?{origin:src3.origin}:{},own,inherited:Boolean(src3&&!own),removed:roles(state2).some((role)=>removed.has(role)),downloadable,...url2?{sourceUrl:url2}:{}}}function localSources(name){return sourceFiles(name).map((file2)=>({file:file2,path:join14(sourceDir(name),file2),...roleOf(file2)?{role:roleOf(file2)}:{}}))}function hasLocalSource(name){if(sourceFiles(name).length>0)return!0;return Object.values(readStudio(name)?.sources??{}).some((value)=>typeof value==="string"&&fileOk(value)&&existsSync17(sourcePath(name,value)))}function sourceStamp(name){let src3=sourceDir(name),stats=[studioFile(name),existsSync17(file(name))?file(name):""].filter(Boolean).map((path7)=>{try{let st=statSync6(path7);return`${basename11(path7)}:${st.mtimeMs}:${st.size}`}catch{return`${basename11(path7)}:missing`}}),media=sourceFiles(name).sort().map((f)=>{try{let st=statSync6(join14(src3,f));return`${f}:${st.mtimeMs}:${st.size}`}catch{return`${f}:missing`}});return[...stats,...media].join("|")}function findSource(name,state2){return sourceStatus(name,state2).path}function adopt(name,from2,role="base"){let fname=`${role}${extname3(from2).toLowerCase()}`,dst=join14(ensure(name).source,fname);if(from2!==dst)copyFileSync2(from2,dst);return fname}function readStudio(name){let p=studioFile(name);if(!existsSync17(p))return;let raw2=JSON.parse(readFileSync10(p,"utf8"));if(!raw2||typeof raw2!=="object")return;return normalizeStudioSources(name,raw2)}function writeStudio(name,s){ensure(name),writeFileSync5(studioFile(name),JSON.stringify(s,null,2)+`
|
|
4152
4151
|
`,"utf8")}function header(path7){if(!existsSync17(path7))return;return peek2(path7)??void 0}function baked(name){let local=file(name);if(existsSync17(local))return local;let target=(name==="default"?"nous":name).toLowerCase();for(let e of listEikons([BUNDLED_EIKON_DIR]))if(basename11(dirname11(e.path)).toLowerCase()===target||e.meta.name.toLowerCase()===target)return e.path;return}var registry=new Map(BUILTIN.map((r)=>[r.name,r])),subs2=new Set;function register(r){registry.set(r.name,r);for(let f of subs2)f();return()=>{if(registry.get(r.name)===r)registry.delete(r.name);for(let f of subs2)f()}}var rasterizers=()=>[...registry.values()],rasterizer=(name)=>registry.get(name),onRegistry=(fn)=>{return subs2.add(fn),()=>subs2.delete(fn)};function pick(prefer){let want=prefer&®istry.get(prefer);if(want&&want.available()===!0)return want;for(let r of registry.values())if(r.available()===!0)return r;return registry.get("native")}var rev=0,revSubs=new Set,revision=()=>rev,onRevision=(fn)=>{return revSubs.add(fn),()=>revSubs.delete(fn)},bump=()=>{rev++;for(let f of revSubs)f()},notifyRevision=bump;function serialize2(name,fps,clips2){let records=[{type:"header",eikon:1,id:name,title:name,author:{name:process.env.USER??"unknown"},size:{cols:W2,rows:H},defaultSignal:"state.idle",signals:defaultSignalMappings()}];for(let st of STATES2){let fs7=clips2.get(st);records.push({type:"clip",name:st,fps,frameCount:fs7.length,loopFrom:0}),fs7.forEach((f,i)=>records.push({type:"frame",clip:st,index:i,rows:f}))}return serializeLaunchStream(records)}function preserve(name,src3){if(!src3)return;let man=manifest2(name)??{name};if(origin(man))return;writeFileSync5(join14(dir(name),"manifest.json"),JSON.stringify({...man,origin:{source:src3,at:new Date().toISOString()}},null,2)+`
|
|
4153
4152
|
`,"utf8")}async function save2(s){let r=rasterizer(s.rasterizer)??pick(s.rasterizer),paths=ensure(s.name),sources={};for(let[role,p]of Object.entries(s.sources)){if(p===null){sources[role]=null;continue}if(!p)continue;let abs2=p.includes("/")?p:join14(paths.source,p);sources[role]=existsSync17(abs2)?adopt(s.name,abs2,role):p}let seen=new Map,clips2=new Map,blank=[Array.from({length:H},(_2,i)=>(i===H>>1?s.glyph.padStart(W2>>1):"").padEnd(W2))];for(let st of STATES2){let src3=sourceStatus(s.name,st,{sources}).path,k2=eff(s,st),key3=`${src3??""}|${JSON.stringify(k2)}`,fs7=seen.get(key3);if(!fs7){if(!src3)fs7=blank;else{let out=await cached2(r,src3,s.spatial,s.tone,s.fps,k2);if("err"in out)throw Error(out.err);fs7=out.frames}seen.set(key3,fs7)}clips2.set(st,fs7)}let head=header(paths.file);return preserve(s.name,legacySource(head)),await Bun.write(paths.file,serialize2(s.name,s.fps,clips2)),writeStudio(s.name,{...toStudio(s),sources}),bump(),paths.file}function useInstalled(name){if(!existsSync17(file(name))&&!baked(name))throw Error(`eikon '${name}' is not installed`);set("eikon",name),bump()}function remove2(name,opts={}){if(get2("eikon")===name&&!opts.confirmActive)return{type:"active-consequence",action:"remove",name,message:`Removing '${name}' will clear the active avatar. Pass confirmActive to remove it.`};if(rmSync3(dir(name),{recursive:!0,force:!0}),get2("eikon")===name)set("eikon",void 0);bump();return}async function update(name,opts={}){if(get2("eikon")===name&&!opts.confirmActive)return{type:"active-consequence",action:"update",name,message:`Updating '${name}' will change the active avatar's backing package. Pass confirmActive to update it.`};let info2=lifecycle(name),src3=info2.source.origin??info2.source.packageUrl;if(!src3)throw Error(`eikon '${name}' has no recorded source`);return fetchSource(src3,{name})}var peekSource=peek3;function stripManifestTrust(name){let p=join14(dir(name),"manifest.json");if(!existsSync17(p))return;let man=JSON.parse(readFileSync10(p,"utf8"));if(!("license"in man)&&!("provenance"in man))return;delete man.license,delete man.provenance,writeFileSync5(p,JSON.stringify(man,null,2)+`
|
|
4154
|
-
`,"utf8")}function statResolved(r){let xs=entries(r.manifest),files=Array.isArray(r.manifest.files)?r.manifest.files:[],sizes=xs.map(([,rel2])=>files.find((f)=>f.path===rel2)?.size);if(sizes.every((n)=>typeof n==="number"))return{n:xs.length,bytes:sizes.reduce((a,b2)=>a+b2,0)};if(r.staged)return{n:xs.length,bytes:xs.reduce((sum,[,rel2])=>{let p=join14(r.staged,rel2);return existsSync17(p)?sum+statSync6(p).size:sum},0)};return}async function inspectSource(src3){let dl=/^http:\/\/localhost[:/]/.test(src3)?{allowPrivate:!0}:void 0,r=await resolve6(src3,{downloader:dl});return inspectResolved(src3,r,statResolved(r))}function attachSources(name,sources){let prev=readStudio(name);writeStudio(name,{...prev??toStudio(fresh(name,pick())),sources:{...prev?.sources,...sources}}),bump()}function digest(data2){return`sha256:${createHash3("sha256").update(data2).digest("hex")}`}function dlOpts(url2,opts={}){return/^http:\/\/localhost[:/]/.test(url2)?{allowPrivate:!0,...opts}:opts}function manUrl(url2){if(url2.endsWith("manifest.json"))return url2;return new URL("manifest.json",url2.endsWith("/")?url2:`${url2}/`).toString()}function specOf(man,rel2){return(Array.isArray(man.files)?man.files:[]).find((f)=>OBJ(f)&&f.path===rel2)}async function readManifest(url2,opts){let raw2=await downloadBytes(url2,opts),man=JSON.parse(Buffer.from(raw2).toString("utf8"));if(!OBJ(man))throw Error("source manifest: object required");return man}async function readSource(file2,base2,rel2,opts){let raw2=await downloadBytes(new URL(rel2,base2).toString(),opts),size=file2?.size;if(typeof size==="number"&&raw2.length!==size)throw Error(`source size mismatch: ${rel2}`);if(typeof file2?.digest==="string"&&digest(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}async function downloadSource(name,opts={}){let url2=sourceFetchUrl(name);if(!url2)throw Error(`eikon '${name}' has no published source`);let href=manUrl(url2),root2=href.slice(0,href.lastIndexOf("/")+1),dl=dlOpts(url2,opts.downloader),man=await readManifest(href,dl),xs=sourceEntries(man,!0);if(xs.length===0)throw Error(`eikon '${name}' has no published source media`);let dir2=ensure(name).source,pairs=await Promise.all(xs.map(async([role,rel2])=>{let file2=specOf(man,rel2),fname=sourceName(man,role,rel2);if(!fileOk(fname))throw Error(`source media type unsupported: ${rel2}`);return[role,fname,await readSource(file2,root2,rel2,dl)]})),sources={};return await Promise.all(pairs.map(async([role,fname,data2])=>{await Bun.write(join14(dir2,fname),data2),sources[role]=fname})),attachSources(name,sources),{name,sources,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}async function fetchSource(src3,opts){let out=await install(src3,ROOT(),opts);stripManifestTrust(out.name);let sources=normalizeSources(out.name,out.sources);return attachSources(out.name,sources),{name:out.name,sources,n:out.n,bytes:out.bytes}}var SAFE=/^[a-zA-Z0-9._/-]+$/;function safePath(path7){if(!path7||path7.startsWith("/")||path7.startsWith("./")||path7.includes("../")||path7==="..")return!1;if(!SAFE.test(path7))return!1;return!path7.split("/").includes("..")}function pkgErr(path7,msg){return Error(`${path7}: ${msg}`)}function launchOk(range){let lower=range.match(/>=?\s*(\d+)/);if(lower&&Number(lower[1])>1)return!1;let exact=range.match(/^\s*(\d+)(?:\.\d+)?\s*$/);if(exact&&Number(exact[1])!==1)return!1;if(/>=?\s*2\b|\^\s*2\b/.test(range))return!1;return!/^\s*>=?\s*99/.test(range)}function validatePkg(value){if(!OBJ(value))throw pkgErr("manifest","object required");let man=value;if(man.kind!=="eikon.package")throw pkgErr("kind","must be eikon.package");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(String(man.name??"")))throw pkgErr("name","safe package name required");if(!man.id||typeof man.id!=="string")throw pkgErr("id","safe id required");if(!OBJ(man.compatibility)||typeof man.compatibility.eikon!=="string")throw pkgErr("compatibility.eikon","required");if(!launchOk(man.compatibility.eikon))throw pkgErr("compatibility.eikon","must support launch major version 1");if(!OBJ(man.entrypoints)||typeof man.entrypoints.default!=="string"||!safePath(man.entrypoints.default))throw pkgErr("entrypoints.default","safe relative path required");for(let[k2,p]of Object.entries(man.entrypoints))if(typeof p!=="string"||!safePath(p))throw pkgErr(`entrypoints.${k2}`,"safe relative path required");for(let f of man.files??[])if(!f||typeof f.path!=="string"||!safePath(f.path))throw pkgErr("files.path","safe relative path required");if(man.poster&&!safePath(man.poster))throw pkgErr("poster","safe relative path required");return man}function asUrl(value,base2){if(/^file:\/\//.test(value))return value;let out=new URL(value,base2);if(out.protocol!=="http:"&&out.protocol!=="https:")throw pkgErr("packageUrl","http(s) URL required");return out.toString()}function relUrl(base2,path7){if(!path7)return;if(/^(https?|file):\/\//.test(path7))return asUrl(path7);if(!safePath(path7))throw pkgErr("path","safe relative path required");return new URL(path7,base2).toString()}function entryState(name,available=!0){if(!available)return"incompatible";if(get2("eikon")===name)return"active";if(existsSync17(file(name)))return"installed";return"available"}function normalize2(input,base2){if(!OBJ(input))throw pkgErr("catalog","entry object required");if(input.kind==="eikon.catalog.entry"){let entry2=input;return{...entry2,state:entryState(entry2.name,entry2.compatibility?.available!==!1)}}if(OBJ(input.manifest)&&typeof input.packageUrl==="string"){let man=validatePkg(input.manifest),packageUrl2=asUrl(input.packageUrl,base2),root2=packageUrl2.slice(0,packageUrl2.lastIndexOf("/")+1);return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:man.id,sourceKey:typeof input.sourceKey==="string"?input.sourceKey:packageUrl2,name:man.name,title:man.display?.title,author:man.display?.author,description:man.display?.description,glyph:man.display?.glyph,tags:man.display?.tags,poster:relUrl(root2,man.poster),packageUrl:packageUrl2,detailUrl:typeof input.detailUrl==="string"?asUrl(input.detailUrl,root2):void 0,compatibility:{eikon:man.compatibility.eikon,hosts:man.compatibility.hosts,available:launchOk(man.compatibility.eikon)},state:entryState(man.name,launchOk(man.compatibility.eikon))}}let name=String(input.name??"");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(name))throw pkgErr("name","safe catalog name required");let source=typeof input.source==="string"?input.source:`${name}/`,packageUrl=/^(https?|file):\/\//.test(source)?asUrl(source):base2?new URL(source,base2).toString():source,manifest3=packageUrl.endsWith("manifest.json")?packageUrl:new URL("manifest.json",packageUrl.endsWith("/")?packageUrl:`${packageUrl}/`).toString();return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:name,sourceKey:packageUrl,name,author:typeof input.author==="string"?input.author:void 0,title:typeof input.title==="string"?input.title:void 0,description:typeof input.description==="string"?input.description:void 0,tags:Array.isArray(input.tags)?input.tags.filter((x2)=>typeof x2==="string"):void 0,glyph:typeof input.glyph==="string"?input.glyph:void 0,poster:typeof input.poster==="string"?input.poster:void 0,packageUrl:manifest3,compatibility:{eikon:">=1 <2",available:!0},state:entryState(name)}}async function loadText(url2,fetcher=fetch){if(url2.startsWith("file://"))return readFileSync10(new URL(url2),"utf8");let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);return await res.text()}async function loadBytes(url2,fetcher=fetch,desc){if(url2.startsWith("file://"))return new Uint8Array(readFileSync10(new URL(url2)));let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);let enc2=res.headers.get("content-encoding");if(enc2&&enc2.toLowerCase()!=="identity"&&desc?.digest)throw pkgErr("runtime",`artifact must be served without Content-Encoding: ${enc2}`);return new Uint8Array(await res.arrayBuffer())}async function loadJson(url2,fetcher=fetch){return JSON.parse(await loadText(url2,fetcher))}async function loadCatalog2(index=process.env.HERM_EIKON_MARKETPLACE||DEFAULT_PUBLIC_CATALOG,fetcher=fetch){let url2=index.endsWith("index.json")?index:`${index.replace(/\/$/,"")}/index.json`,raw2=await loadJson(url2,fetcher);if(!Array.isArray(raw2))throw pkgErr("catalog","index array required");let base2=url2.slice(0,url2.lastIndexOf("/")+1);return raw2.map((item)=>normalize2(item,base2))}async function adaptPackage(manifest3,streamText,legacyText){let man=validatePkg(manifest3),body=streamText??legacyText;if(!body)throw pkgErr("entrypoints.default","stream data required");let eik=parseEikon(body);for(let st of STATES2)if(!eik.states.has(st))throw pkgErr(`states.${st}`,"canonical lifecycle state required");return{manifest:man,eikon:eik,states:[...STATES2],triggers:man.triggers,extensions:man.extensions}}async function loadPackage(url2,fetcher=fetch){return{man:validatePkg(await loadJson(url2,fetcher)),base:url2.slice(0,url2.lastIndexOf("/")+1)}}function runtimeDesc2(man,path7=man.entrypoints.default){let file2=man.files?.find((f)=>f.path===path7)??man.files?.find((f)=>f.role==="runtime");if(!file2||!file2.digest&&file2.size==null&&!file2.encoding&&file2.decodedSize==null&&!file2.decodedDigest)return;return{digest:file2.digest,size:file2.size,encoding:file2.encoding,decodedSize:file2.decodedSize,decodedDigest:file2.decodedDigest}}async function loadRuntime(man,base2,fetcher=fetch,path7=man.entrypoints.default){let desc=runtimeDesc2(man,path7),bytes=await loadBytes(new URL(path7,base2).toString(),fetcher,desc);return{bytes,text:decodeRuntimeBytes(bytes,{descriptor:desc})}}async function previewPackage(entry2,fetcher=fetch){let{man,base:base2}=await loadPackage(entry2.packageUrl,fetcher);return adaptPackage(man,(await loadRuntime(man,base2,fetcher)).text)}async function installPackage(src3,opts={}){let url2=typeof src3==="string"?src3:src3.packageUrl;return fetchSource(url2,{name:opts.name,downloader:opts.fetcher?{fetcher:opts.fetcher}:void 0})}var TOKEN2=/(gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|Bearer\s+[A-Za-z0-9._~+/=-]+|token\s+[A-Za-z0-9._~+/=-]+|\*{3,})/gi;function submitPath(name){return file(name)}function publishedInfo(path7){let head=header(path7);if(typeof head?.source_url==="string"&&head.source_url.trim())return{source:head.source_url};let mf=join15(dirname12(path7),"manifest.json");if(!existsSync18(mf))return;try{let man=JSON.parse(readFileSync11(mf,"utf8")),src3=man.origin?.source??man.sourceUrl??man.source_url;if(typeof src3==="string"&&src3.trim())return{source:src3}}catch{}return}function redact2(message){return message.replace(TOKEN2,"[redacted]")}function failureText(xs){return xs.map((x2)=>redact2(x2.message)).join(`
|
|
4155
|
-
`)}async function
|
|
4156
|
-
|
|
4157
|
-
`)
|
|
4153
|
+
`,"utf8")}function statResolved(r){let xs=entries(r.manifest),files=Array.isArray(r.manifest.files)?r.manifest.files:[],sizes=xs.map(([,rel2])=>files.find((f)=>f.path===rel2)?.size);if(sizes.every((n)=>typeof n==="number"))return{n:xs.length,bytes:sizes.reduce((a,b2)=>a+b2,0)};if(r.staged)return{n:xs.length,bytes:xs.reduce((sum,[,rel2])=>{let p=join14(r.staged,rel2);return existsSync17(p)?sum+statSync6(p).size:sum},0)};return}async function inspectSource(src3){let dl=/^http:\/\/localhost[:/]/.test(src3)?{allowPrivate:!0}:void 0,r=await resolve6(src3,{downloader:dl});return inspectResolved(src3,r,statResolved(r))}function attachSources(name,sources){let prev=readStudio(name);writeStudio(name,{...prev??toStudio(fresh(name,pick())),sources:{...prev?.sources,...sources}}),bump()}function digest(data2){return`sha256:${createHash3("sha256").update(data2).digest("hex")}`}function dlOpts(url2,opts={}){return/^http:\/\/localhost[:/]/.test(url2)?{allowPrivate:!0,...opts}:opts}function manUrl(url2){if(url2.endsWith("manifest.json"))return url2;return new URL("manifest.json",url2.endsWith("/")?url2:`${url2}/`).toString()}function specOf(man,rel2){return(Array.isArray(man.files)?man.files:[]).find((f)=>OBJ(f)&&f.path===rel2)}async function readManifest(url2,opts){let raw2=await downloadBytes(url2,opts),man=JSON.parse(Buffer.from(raw2).toString("utf8"));if(!OBJ(man))throw Error("source manifest: object required");return man}async function readSource(file2,base2,rel2,opts){let raw2=await downloadBytes(new URL(rel2,base2).toString(),opts),size=file2?.size;if(typeof size==="number"&&raw2.length!==size)throw Error(`source size mismatch: ${rel2}`);if(typeof file2?.digest==="string"&&digest(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}async function downloadSource(name,opts={}){let url2=sourceFetchUrl(name);if(!url2)throw Error(`eikon '${name}' has no published source`);let href=manUrl(url2),root2=href.slice(0,href.lastIndexOf("/")+1),dl=dlOpts(url2,opts.downloader),man=await readManifest(href,dl),xs=sourceEntries(man,!0);if(xs.length===0)throw Error(`eikon '${name}' has no published source media`);let dir2=ensure(name).source,pairs=await Promise.all(xs.map(async([role,rel2])=>{let file2=specOf(man,rel2),fname=sourceName(man,role,rel2);if(!fileOk(fname))throw Error(`source media type unsupported: ${rel2}`);return[role,fname,await readSource(file2,root2,rel2,dl)]})),sources={};return await Promise.all(pairs.map(async([role,fname,data2])=>{await Bun.write(join14(dir2,fname),data2),sources[role]=fname})),attachSources(name,sources),{name,sources,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}async function fetchSource(src3,opts){let out=await install(src3,ROOT(),opts);stripManifestTrust(out.name);let sources=normalizeSources(out.name,out.sources);return attachSources(out.name,sources),{name:out.name,sources,n:out.n,bytes:out.bytes}}var SAFE=/^[a-zA-Z0-9._/-]+$/;function safePath(path7){if(!path7||path7.startsWith("/")||path7.startsWith("./")||path7.includes("../")||path7==="..")return!1;if(!SAFE.test(path7))return!1;return!path7.split("/").includes("..")}function pkgErr(path7,msg){return Error(`${path7}: ${msg}`)}function launchOk(range){let lower=range.match(/>=?\s*(\d+)/);if(lower&&Number(lower[1])>1)return!1;let exact=range.match(/^\s*(\d+)(?:\.\d+)?\s*$/);if(exact&&Number(exact[1])!==1)return!1;if(/>=?\s*2\b|\^\s*2\b/.test(range))return!1;return!/^\s*>=?\s*99/.test(range)}function validatePkg(value){if(!OBJ(value))throw pkgErr("manifest","object required");let man=value;if(man.kind!=="eikon.package")throw pkgErr("kind","must be eikon.package");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(String(man.name??"")))throw pkgErr("name","safe package name required");if(!man.id||typeof man.id!=="string")throw pkgErr("id","safe id required");if(!OBJ(man.compatibility)||typeof man.compatibility.eikon!=="string")throw pkgErr("compatibility.eikon","required");if(!launchOk(man.compatibility.eikon))throw pkgErr("compatibility.eikon","must support launch major version 1");if(!OBJ(man.entrypoints)||typeof man.entrypoints.default!=="string"||!safePath(man.entrypoints.default))throw pkgErr("entrypoints.default","safe relative path required");for(let[k2,p]of Object.entries(man.entrypoints))if(typeof p!=="string"||!safePath(p))throw pkgErr(`entrypoints.${k2}`,"safe relative path required");for(let f of man.files??[])if(!f||typeof f.path!=="string"||!safePath(f.path))throw pkgErr("files.path","safe relative path required");if(man.poster&&!safePath(man.poster))throw pkgErr("poster","safe relative path required");return man}function asUrl(value,base2){if(/^file:\/\//.test(value))return value;let out=new URL(value,base2);if(out.protocol!=="http:"&&out.protocol!=="https:")throw pkgErr("packageUrl","http(s) URL required");return out.toString()}function relUrl(base2,path7){if(!path7)return;if(/^(https?|file):\/\//.test(path7))return asUrl(path7);if(!safePath(path7))throw pkgErr("path","safe relative path required");return new URL(path7,base2).toString()}function entryState(name,available=!0){if(!available)return"incompatible";if(get2("eikon")===name)return"active";if(existsSync17(file(name)))return"installed";return"available"}function normalize2(input,base2){if(!OBJ(input))throw pkgErr("catalog","entry object required");if(input.kind==="eikon.catalog.entry"){let entry2=input;return{...entry2,state:entryState(entry2.name,entry2.compatibility?.available!==!1)}}if(OBJ(input.manifest)&&typeof input.packageUrl==="string"){let man=validatePkg(input.manifest),packageUrl2=asUrl(input.packageUrl,base2),root2=packageUrl2.slice(0,packageUrl2.lastIndexOf("/")+1);return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:man.id,sourceKey:typeof input.sourceKey==="string"?input.sourceKey:packageUrl2,name:man.name,title:man.display?.title,author:man.display?.author,description:man.display?.description,glyph:man.display?.glyph,tags:man.display?.tags,poster:relUrl(root2,man.poster),packageUrl:packageUrl2,detailUrl:typeof input.detailUrl==="string"?asUrl(input.detailUrl,root2):void 0,compatibility:{eikon:man.compatibility.eikon,hosts:man.compatibility.hosts,available:launchOk(man.compatibility.eikon)},state:entryState(man.name,launchOk(man.compatibility.eikon))}}let name=String(input.name??"");if(!/^[a-z0-9][a-z0-9-]{1,63}$/.test(name))throw pkgErr("name","safe catalog name required");let source=typeof input.source==="string"?input.source:`${name}/`,packageUrl=/^(https?|file):\/\//.test(source)?asUrl(source):base2?new URL(source,base2).toString():source,manifest3=packageUrl.endsWith("manifest.json")?packageUrl:new URL("manifest.json",packageUrl.endsWith("/")?packageUrl:`${packageUrl}/`).toString();return{kind:"eikon.catalog.entry",schemaVersion:"1.0",id:name,sourceKey:packageUrl,name,author:typeof input.author==="string"?input.author:void 0,title:typeof input.title==="string"?input.title:void 0,description:typeof input.description==="string"?input.description:void 0,tags:Array.isArray(input.tags)?input.tags.filter((x2)=>typeof x2==="string"):void 0,glyph:typeof input.glyph==="string"?input.glyph:void 0,poster:typeof input.poster==="string"?input.poster:void 0,packageUrl:manifest3,compatibility:{eikon:">=1 <2",available:!0},state:entryState(name)}}async function loadText(url2,fetcher=fetch){if(url2.startsWith("file://"))return readFileSync10(new URL(url2),"utf8");let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);return await res.text()}async function loadBytes(url2,fetcher=fetch,desc){if(url2.startsWith("file://"))return new Uint8Array(readFileSync10(new URL(url2)));let res=await fetcher(url2);if(!res.ok)throw Error(`fetch: ${res.status} ${url2}`);let enc2=res.headers.get("content-encoding");if(enc2&&enc2.toLowerCase()!=="identity"&&desc?.digest)throw pkgErr("runtime",`artifact must be served without Content-Encoding: ${enc2}`);return new Uint8Array(await res.arrayBuffer())}async function loadJson(url2,fetcher=fetch){return JSON.parse(await loadText(url2,fetcher))}async function loadCatalog2(index=process.env.HERM_EIKON_MARKETPLACE||DEFAULT_PUBLIC_CATALOG,fetcher=fetch){let url2=index.endsWith("index.json")?index:`${index.replace(/\/$/,"")}/index.json`,raw2=await loadJson(url2,fetcher);if(!Array.isArray(raw2))throw pkgErr("catalog","index array required");let base2=url2.slice(0,url2.lastIndexOf("/")+1);return raw2.map((item)=>normalize2(item,base2))}async function adaptPackage(manifest3,streamText,legacyText){let man=validatePkg(manifest3),body=streamText??legacyText;if(!body)throw pkgErr("entrypoints.default","stream data required");let eik=parseEikon(body);for(let st of STATES2)if(!eik.states.has(st))throw pkgErr(`states.${st}`,"canonical lifecycle state required");return{manifest:man,eikon:eik,states:[...STATES2],triggers:man.triggers,extensions:man.extensions}}async function loadPackage(url2,fetcher=fetch){return{man:validatePkg(await loadJson(url2,fetcher)),base:url2.slice(0,url2.lastIndexOf("/")+1)}}function runtimeDesc2(man,path7=man.entrypoints.default){let file2=man.files?.find((f)=>f.path===path7)??man.files?.find((f)=>f.role==="runtime");if(!file2||!file2.digest&&file2.size==null&&!file2.encoding&&file2.decodedSize==null&&!file2.decodedDigest)return;return{digest:file2.digest,size:file2.size,encoding:file2.encoding,decodedSize:file2.decodedSize,decodedDigest:file2.decodedDigest}}async function loadRuntime(man,base2,fetcher=fetch,path7=man.entrypoints.default){let desc=runtimeDesc2(man,path7),bytes=await loadBytes(new URL(path7,base2).toString(),fetcher,desc);return{bytes,text:decodeRuntimeBytes(bytes,{descriptor:desc})}}async function previewPackage(entry2,fetcher=fetch){let{man,base:base2}=await loadPackage(entry2.packageUrl,fetcher);return adaptPackage(man,(await loadRuntime(man,base2,fetcher)).text)}async function installPackage(src3,opts={}){let url2=typeof src3==="string"?src3:src3.packageUrl;return fetchSource(url2,{name:opts.name,downloader:opts.fetcher?{fetcher:opts.fetcher}:void 0})}var TOKEN=/(gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|Bearer\s+[A-Za-z0-9._~+/=-]+|token\s+[A-Za-z0-9._~+/=-]+|\*{3,})/gi,CTRL2=/[\u0000-\u001f\u007f-\u009f]/,SECRET2=/(\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|id_rsa$|id_ed25519$|token|secret|credential|password)/i,REPO=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,DEFAULT_REPO=process.env.EIKON_REPO??"liftaris/eikon";function submitPath(name){return file(name)}function targetRepo(){return DEFAULT_REPO}function publishedInfo(path7){let head=header(path7);if(typeof head?.source_url==="string"&&head.source_url.trim())return{source:head.source_url};let mf=join15(dirname12(path7),"manifest.json");if(!existsSync18(mf))return;try{let man=JSON.parse(readFileSync11(mf,"utf8")),src3=man.origin?.source??man.sourceUrl??man.source_url;if(typeof src3==="string"&&src3.trim())return{source:src3}}catch{}return}function redact(message){return message.replace(TOKEN,"[redacted]")}function failureText(xs){return xs.map((x2)=>redact(x2.message)).join(`
|
|
4154
|
+
`)}async function defaults2(input){let bundle;try{bundle=await previewSubmitBundle({path:input.path})}catch{}let meta=bundle?.meta,name=typeof meta?.name==="string"?meta.name:basename12(input.path).replace(/\.eikon$/i,""),author=authorName(meta?.author)??await ghUser()??process.env.USER??"unknown",glyph=typeof meta?.glyph==="string"&&meta.glyph.trim()?meta.glyph.trim():"\u25C6";return{title:typeof meta?.title==="string"&&meta.title.trim()?meta.title.trim():name,author,description:"Monochrome terminal avatar.",glyph}}async function prepare(input){let base2=await previewSubmitBundle({path:input.path}),meta=sanitize2(input.meta??await defaults2(input)),target=repo(input.target??DEFAULT_REPO),rel2=`eikon-submissions/${base2.meta.name}-${Date.now()}-${Math.random().toString(36).slice(2)}/${base2.meta.name}`,root2=hermesPath(rel2);mkdirSync5(root2,{recursive:!0}),stage(base2,root2,meta,input.includeSource===!0);let bundle=await previewSubmitBundle({path:join15(root2,basename12(base2.packed))}),req=request(bundle,meta,target);return{path:input.path,name:bundle.meta.name,files:bundle.files.map((f)=>({path:f.path,bytes:f.bytes})),meta,target,source:input.includeSource===!0,bundleDir:root2,bundleSource:makeSource(rel2,rel2),title:req.title,body:req.body,url:fallbackUrl(target,bundle.meta.name),steps:steps(target,bundle.meta.name),bundle,request:req,snapshot:snap(bundle)}}async function submit2(input,backend3){let bundle;try{bundle=await previewSubmitBundle({path:join15(input.bundleDir,basename12(input.bundle.packed))})}catch(err){return{kind:"validation-failed",failures:[{code:"invalid-eikon",message:err instanceof Error?err.message:String(err)}]}}if(snap(bundle)!==input.snapshot)return{kind:"validation-failed",failures:[{code:"invalid-eikon",message:"staged submission changed after preview; review the bundle again"}]};let be2=backend3??githubSubmitBackend(input.target),setup=await be2.check();if(!setup.ok)return{kind:"setup-needed",failures:[{code:"missing-auth",message:redact(setup.reason)}]};try{return await be2.create(request(bundle,input.meta,input.target))}catch(err){return{kind:"backend-failed",failures:[{code:"backend-failed",message:redact(err instanceof Error?err.message:String(err))}]}}}function stage(bundle,root2,meta,source){let picked=source?bundle.files:bundle.files.filter((f)=>f.abs===bundle.packed||f.path===basename12(bundle.packed));for(let entry2 of picked){if(entry2.path==="manifest.json")continue;let out=join15(root2,entry2.path);mkdirSync5(dirname12(out),{recursive:!0}),copyFileSync3(entry2.abs,out)}let old=source&&existsSync18(join15(bundle.root,"manifest.json"))?JSON.parse(readFileSync11(join15(bundle.root,"manifest.json"),"utf8")):{};writeFileSync6(join15(root2,"manifest.json"),JSON.stringify({name:bundle.meta.name,version:typeof old.version==="number"?old.version:1,...typeof old.eikon_requires==="string"?{eikon_requires:old.eikon_requires}:{},...source&&typeof old.source==="string"?{source:old.source}:{},states:source&&old.states&&typeof old.states==="object"&&!Array.isArray(old.states)?old.states:{},display:{title:meta.title,author:meta.author,description:meta.description,glyph:meta.glyph}},null,2)+`
|
|
4155
|
+
`,"utf8")}function request(bundle,meta,target){let title=`eikons: submit ${bundle.meta.name}`,body=[`Submits \`${bundle.meta.name}\` for official registry review.`,"",`Title: ${meta.title}`,`Author: ${meta.author}`,`Description: ${meta.description}`,`Glyph: ${meta.glyph}`,`Target: ${target}`,"","Submission bundle:",...bundle.files.map((f)=>`- ${f.path} (${f.bytes} bytes)`),"","This PR makes the listed files public and reviewable. The Eikon is not officially listed or verified until registry review and merge."].join(`
|
|
4156
|
+
`);return{bundle,title,body}}function sanitize2(meta){let next2={title:clean3(meta.title),author:clean3(meta.author),description:clean3(meta.description),glyph:clean3(meta.glyph)},errs=Object.entries(next2).flatMap(([key3,value])=>{if(!value)return[`${key3} required`];if(CTRL2.test(value))return[`${key3} contains control characters`];if(secretLike(value))return[`${key3} looks secret-like`];if(unsafeUrl(value))return[`${key3} contains private or unsafe URL`];return[]});if(Array.from(next2.glyph).length>2)errs.push("glyph must be one or two characters");if(errs.length)throw Error(errs.join(`
|
|
4157
|
+
`));return next2}function secretLike(value){return TOKEN.lastIndex=0,TOKEN.test(value)||SECRET2.test(value)}function clean3(value){return value.trim().replace(/\s+/g," ")}function authorName(value){if(typeof value==="string"&&value.trim())return value.trim();if(value&&typeof value==="object"&&!Array.isArray(value)){let name=value.name;if(typeof name==="string"&&name.trim())return name.trim()}return}function repo(value){let clean4=value.trim();if(!REPO.test(clean4))throw Error(`invalid submit repo: ${value}`);return clean4}function unsafeUrl(value){return(value.match(/\b(?:https?|file|data|javascript):[^\s]+/gi)??[]).some((raw2)=>{let url2;try{url2=new URL(raw2)}catch{return!1}if(url2.protocol!=="http:"&&url2.protocol!=="https:")return!0;return privateHost2(url2.hostname)})}function privateHost2(host){let h2=host.toLowerCase().replace(/^\[|\]$/g,"");if(!h2||h2==="::"||h2==="localhost"||h2.endsWith(".localhost"))return!0;let ipv4=h2.match(/^(\d+)\.(\d+)\./);if(ipv4&&privateIpv42(Number(ipv4[1]),Number(ipv4[2])))return!0;if(h2.startsWith("fe80:")||/^f[cd][0-9a-f]{2}:/.test(h2))return!0;let mapped=h2.match(/^::ffff:(?:(\d+)\.(\d+)\.|([0-9a-f]{1,4}):([0-9a-f]{1,4}))/);if(mapped?.[1]&&privateIpv42(Number(mapped[1]),Number(mapped[2])))return!0;if(mapped?.[3]&&mapped?.[4]){let n=Number.parseInt(mapped[3],16)*65536+Number.parseInt(mapped[4],16);return privateIpv42(Math.floor(n/16777216),Math.floor(n/65536)&255)}return isIP(h2)!==0&&(h2==="0.0.0.0"||h2==="::1")}function privateIpv42(a,b2){if(a===10||a===127)return!0;if(a===169&&b2===254)return!0;if(a===192&&b2===168)return!0;return a===172&&b2>=16&&b2<=31}function fallbackUrl(target,name){return`https://github.com/${target}/compare/main...submit%2F${encodeURIComponent(name)}`}function steps(target,name){return[`Fork or open ${target} on GitHub.`,`Copy the prepared bundle from this machine into eikons/${name}/ on a submit/${name} branch.`,"Open a pull request with the title and body shown here."]}function stageRoot(){let root2=hermesPath("eikon-submissions");return mkdirSync5(root2,{recursive:!0}),root2}function snap(bundle){let hash2=createHash4("sha256");for(let file2 of bundle.files)hash2.update(file2.path),hash2.update("\x00"),hash2.update(String(file2.bytes)),hash2.update("\x00"),hash2.update(readFileSync11(file2.abs)),hash2.update("\x00");return hash2.digest("hex")}async function ghUser(){try{let p=Bun.spawn(["gh","api","user","-q",".login"],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(p.stdout).text(),p.exited]);return code===0&&out.trim()?out.trim():void 0}catch{return}}function cleanup(input){let root2=stageRoot(),parent2=dirname12(input.bundleDir);if(!parent2.startsWith(`${root2}/`))return;rmSync4(parent2,{recursive:!0,force:!0})}var FIELDS2=["title","author","description","glyph"];function openEikonSubmit(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Form3,{...opts,done:()=>{dialog.clear(),resolve4()}}),()=>resolve4())})}var Form3=(props)=>{let theme=useTheme().theme,touched=import_react100.useRef({}),flight=import_react100.useRef(!1),[busy,setBusy]=import_react100.useState(!1),[status,setStatus]=import_react100.useState(""),[result,setResult]=import_react100.useState(null),[prepared,setPrepared]=import_react100.useState(null),[consent,setConsent]=import_react100.useState(!1),[field,setField]=import_react100.useState("title"),[meta,setMeta]=import_react100.useState({title:props.name,author:"unknown",description:"Monochrome terminal avatar.",glyph:"\u25C6"});import_react100.useEffect(()=>{let dead=!1;return touched.current={},defaults2({path:props.path}).then((next2)=>{if(dead)return;setMeta((prev)=>({title:touched.current.title?prev.title:next2.title,author:touched.current.author?prev.author:next2.author,description:touched.current.description?prev.description:next2.description,glyph:touched.current.glyph?prev.glyph:next2.glyph}))}).catch((e)=>setStatus(`Defaults failed: ${redact(e instanceof Error?e.message:String(e))}`)),()=>{dead=!0}},[props.path]);let close=()=>{if(prepared&&!status.includes("fallback"))cleanup(prepared);props.done()},edit2=(key3,value)=>{if(touched.current[key3]=!0,setMeta((m2)=>({...m2,[key3]:value})),prepared)cleanup(prepared);setPrepared(null),setConsent(!1),setResult(null)},prep=async()=>{if(flight.current)return;flight.current=!0,setBusy(!0),setResult(null);try{if(setStatus("Preparing public bundle\u2026"),prepared)cleanup(prepared);let next2=await prepare({path:props.path,meta,includeSource:!1});setPrepared(next2),setConsent(!1),setStatus("Review bundle, then press c to consent")}catch(e){setStatus(`Submit failed: ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},send=async()=>{if(flight.current)return;if(!prepared)return prep();if(!consent){setStatus("Press c to consent before publishing");return}flight.current=!0,setBusy(!0),setResult(null);try{setStatus("Submitting\u2026");let next2=await props.submit(prepared);if(setResult(next2),next2.kind==="submitted")cleanup(prepared),setStatus(`Submitted: ${next2.url}`);else if(next2.kind==="setup-needed")setStatus(`GitHub setup needed; browser fallback ready: ${failureText(next2.failures)}`);else setStatus(`Submit failed; browser fallback ready: ${failureText(next2.failures)}`)}catch(e){setStatus(`Submit failed; browser fallback ready: ${redact(e instanceof Error?e.message:String(e))}`)}finally{flight.current=!1,setBusy(!1)}},open2=()=>{if(!prepared)return;if(!consent){setStatus("Press c to consent before opening browser fallback");return}let ok=openUrl(prepared.url);setStatus(ok?"Opened browser fallback":`Open failed; copy ${prepared.url}`)};useKeyboard((key3)=>{if(key3.name==="escape")return close();if(busy)return;if(key3.name==="tab"&&!prepared){let i=FIELDS2.indexOf(field);setField(FIELDS2[(i+(key3.shift?FIELDS2.length-1:1))%FIELDS2.length]);return}if(key3.name==="c"&&prepared){setConsent((v2)=>!v2),setStatus(!consent?"Consented to public PR submission":"Consent cleared");return}if(key3.name==="o"&&prepared)return open2();if(key3.name==="return")return void send()});let bad=status.startsWith("Submit failed"),warn=status.startsWith("GitHub")||status.includes("fallback")||status.includes("consent");return $jsxs("box",{flexDirection:"column",width:84,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Submit eikon"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[props.name," \xB7 official registry PR"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:targetRepo()})}),$jsx("box",{height:1}),!prepared?$jsx(Meta,{meta,field,setField,setMeta:edit2}):$jsx(Preview,{prepared,consent}),$jsx("box",{height:1}),$jsx("text",{fg:bad?theme.error:warn?theme.warning:theme.textMuted,wrapMode:"word",children:status||(prepared?"c consent \xB7 Enter submit \xB7 o open browser fallback \xB7 Esc cancel":"Tab field \xB7 Enter preview public bundle \xB7 Esc cancel")}),result?.kind==="submitted"?$jsx("text",{fg:theme.accent,children:result.url}):null]})};function Meta(props){return $jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:"gray",children:"Public metadata"}),$jsx(Input2,{label:"title",value:props.meta.title,on:props.field==="title",setOn:()=>props.setField("title"),set:(v2)=>props.setMeta("title",v2)}),$jsx(Input2,{label:"author",value:props.meta.author,on:props.field==="author",setOn:()=>props.setField("author"),set:(v2)=>props.setMeta("author",v2)}),$jsx(Input2,{label:"description",value:props.meta.description,on:props.field==="description",setOn:()=>props.setField("description"),set:(v2)=>props.setMeta("description",v2)}),$jsx(Input2,{label:"glyph",value:props.meta.glyph,on:props.field==="glyph",setOn:()=>props.setField("glyph"),set:(v2)=>props.setMeta("glyph",v2)})]})}function Input2(props){let theme=useTheme().theme;return $jsxs("box",{height:1,flexDirection:"row",onMouseDown:props.setOn,children:[$jsx("box",{width:13,children:$jsxs("text",{fg:props.on?theme.primary:theme.textMuted,children:[props.on?"\u25B8 ":" ",props.label]})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("input",{value:props.value,onInput:props.set,focused:props.on,textColor:theme.text,backgroundColor:theme.backgroundElement,focusedBackgroundColor:theme.backgroundElement})})]})}function Preview(props){let theme=useTheme().theme;return $jsxs("box",{flexDirection:"column",children:[$jsxs("text",{fg:theme.textMuted,children:["Included files (",props.prepared.files.length,") \xB7 ",props.prepared.source?"source included":"runtime-only"]}),props.prepared.files.slice(0,6).map((f)=>$jsxs("text",{fg:theme.text,children:["\u2022 ",f.path," \xB7 ",f.bytes," B"]},f.path)),props.prepared.files.length>6?$jsxs("text",{fg:theme.textMuted,children:["\u2026 ",props.prepared.files.length-6," more"]}):null,$jsxs("text",{fg:theme.textMuted,children:["Title: ",props.prepared.meta.title]}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",props.prepared.meta.author]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Description: ",props.prepared.meta.description]}),$jsxs("text",{fg:theme.textMuted,children:["Glyph: ",props.prepared.meta.glyph]}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:8,children:$jsx("text",{fg:theme.textMuted,children:"Bundle:"})}),$jsx(FileLink,{source:props.prepared.bundleSource,children:props.prepared.bundleDir})]}),$jsx("text",{fg:props.consent?theme.accent:theme.warning,children:props.consent?"\u25CF public PR consent":"\u25CB consent required"}),$jsxs("text",{fg:theme.textMuted,children:["PR title: ",props.prepared.title]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["PR body: ",props.prepared.body]}),$jsx("text",{fg:theme.textMuted,children:"Manual steps:"}),props.prepared.steps.map((step2)=>$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["\u2022 ",step2]},step2)),$jsxs("text",{fg:theme.textMuted,children:["Fallback: ",props.prepared.url]})]})}var exports_eikon_gen={};__export(exports_eikon_gen,{setProbe:()=>setProbe,setImpl:()=>setImpl,probeCached:()=>probeCached,probe:()=>probe2,generate:()=>generate,gen:()=>exports_eikon_gen,current:()=>current});import{existsSync as existsSync19,readFileSync as readFileSync12}from"fs";import{tmpdir as tmpdir3}from"os";import{join as join16}from"path";var ROOT2=()=>hermesPath("hermes-agent"),WIN=process.platform==="win32",PY=()=>{for(let v2 of["venv",".venv"]){let bin=WIN?`${ROOT2()}/${v2}/Scripts/python.exe`:`${ROOT2()}/${v2}/bin/python`;if(existsSync19(bin))return bin}return WIN?"python":"python3"},spawn3=(args)=>{try{return Bun.spawn([PY(),...args],{cwd:ROOT2(),env:env2(),stdout:"pipe",stderr:"pipe"})}catch(e){return e instanceof Error?e:Error(String(e))}};function dotenv(){let out={},path7=hermesPath(".env");if(!existsSync19(path7))return out;for(let raw2 of readFileSync12(path7,"utf8").split(`
|
|
4158
|
+
`)){let ln=raw2.trim();if(!ln||ln.startsWith("#"))continue;let eq3=ln.indexOf("=");if(eq3<1)continue;let k2=ln.slice(0,eq3).replace(/^export\s+/,"").trim(),v2=ln.slice(eq3+1).trim();if(v2.startsWith('"')&&v2.endsWith('"')||v2.startsWith("'")&&v2.endsWith("'"))v2=v2.slice(1,-1);out[k2]=v2}return out}var env2=()=>{let base2=dotenv();for(let[k2,v2]of Object.entries(process.env))if(v2!==void 0)base2[k2]=v2;return base2},q4=(s)=>JSON.stringify(s);function code(kind2,prompt,o){if(kind2==="image")return["from tools.image_generation_tool import _handle_image_generate as g",`print(g({"prompt": ${q4(prompt)}, "aspect_ratio": ${q4(o.aspect??"square")}}))`].join("; ");let args=[`"prompt":${q4(prompt)}`,`"aspect_ratio":${q4(o.aspect??"1:1")}`];if(o.seconds)args.push(`"duration":${o.seconds}`);if(o.seed)args.push(`"image_url":${q4(o.seed)}`);return["from tools.video_generation_tool import _handle_video_generate as g",`print(g({${args.join(",")}}))`].join("; ")}async function probe2(){let root2=ROOT2();if(!existsSync19(root2))return{image:!1,video:!1};let src3=["import json","from tools.image_generation_tool import check_image_generation_requirements as ci","from tools.video_generation_tool import check_video_generation_requirements as cv","print(json.dumps({'image': bool(ci()), 'video': bool(cv())}))"].join("; "),r=spawn3(["-c",src3]);if(r instanceof Error)return{image:!1,video:!1};let out=await new Response(r.stdout).text();if(await r.exited!==0)return{image:!1,video:!1};let last3=out.trim().split(`
|
|
4159
|
+
`).pop();try{return JSON.parse(last3)}catch{return{image:!1,video:!1}}}async function fetchTo(url2,ext){let tmp=join16(tmpdir3(),`eikon-gen-${Date.now()}${ext}`),res=await fetch(url2);if(!res.ok)throw Error(`download ${res.status}`);return await Bun.write(tmp,await res.arrayBuffer()),tmp}var generate=async(kind2,prompt,opts)=>{let r=spawn3(["-c",code(kind2,prompt,opts)]);if(r instanceof Error)return{err:r.message};let[out,err,exit]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);if(exit!==0)return{err:(err||out).trim().split(`
|
|
4158
4160
|
`).slice(-3).join(" ")||`python exited ${exit}`};let last3=out.trim().split(`
|
|
4159
|
-
`).pop();if(!last3)return{err:"no output"};let j2;try{j2=JSON.parse(last3)}catch{return{err:`unparseable: ${last3.slice(0,200)}`}}if(j2.success===!1||j2.error)return{err:String(j2.error??"provider error")};let ref=j2.image??j2.video;if(!ref)return{err:"provider returned no asset"};if(ref.startsWith("/")||ref.startsWith("file://"))return{path:ref.replace(/^file:\/\//,"")};if(/^https?:\/\//.test(ref))return fetchTo(ref,kind2==="image"?".png":".mp4").then((p)=>({path:p})).catch((e)=>({err:`download: ${e instanceof Error?e.message:e}`}));return{err:`unrecognized asset ref: ${ref.slice(0,80)}`}},impl=generate,probeImpl=probe2,current=()=>impl,setImpl=(fn)=>{impl=fn??generate},setProbe=(fn)=>{probeImpl=fn??probe2},probeCached=()=>probeImpl();var import_react102=__toESM(require_react_production(),1);var ORDER4=["name","from"],FROMS=[{id:"blank",label:"blank",hint:"author in Studio"},{id:"file",label:"local file",hint:"png / jpg / webp / gif / mp4"},{id:"install",label:"inspect/install",hint:"catalog name \xB7 github.com/u/r/name \xB7 local dir"}],INSTALL_HINT="catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir";function openNewEikon(dialog,opts={}){return new Promise((resolve4)=>{let chained=!1;dialog.replace($jsx(Form4,{initial:opts.initial,dialog,onChain:()=>{chained=!0},done:(r)=>{chained=!0,dialog.clear(),resolve4(r)}}),()=>{if(!chained)resolve4(null)})})}var Form4=(props)=>{let theme=useTheme().theme,[name,setName]=import_react102.useState(props.initial??""),[from2,setFrom]=import_react102.useState("blank"),[field,setField]=import_react102.useState("name"),slug3=name?exports_eikon_knobs.slug(name):"",ok=slug3.length>0,submit3=async()=>{if(!ok)return;if(from2==="blank")return props.done({name:slug3,from:"blank"});if(props.onChain(),from2==="file"){let file2=await openTextPrompt(props.dialog,{title:"Source file",label:"absolute or ~ path (png / jpg / webp / gif / mp4)"});return props.done(file2?{name:slug3,from:"file",file:file2}:null)}let src3=await openTextPrompt(props.dialog,{title:"Inspect eikon source",label:INSTALL_HINT});if(!src3)return props.done(null);try{let info2=await exports_eikon.inspectSource(src3),ok2=await openConfirm(props.dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use the
|
|
4160
|
-
`),yes:"install",no:"cancel"});return props.done(ok2?{name:slug3,from:"install",src:src3}:null)}catch(e){return await openConfirm(props.dialog,{title:"Inspect failed",danger:!0,body:e instanceof Error?e.message:String(e),yes:"ok",no:"cancel"}),props.done(null)}};useKeyboard((key3)=>{if(key3.name==="escape")return props.done(null);if(key3.name==="tab"){let i=ORDER4.indexOf(field);return setField(ORDER4[(i+(key3.shift?-1:1)+ORDER4.length)%ORDER4.length])}if(key3.name==="return")return void submit3();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9 _-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(key3.name==="up"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.max(0,i-1)].id)}if(key3.name==="down"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.min(FROMS.length-1,i+1)].id)}});let bg2=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New eikon"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("name"),children:[$jsx("box",{width:9,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:slug3?` \u2192 ${slug3}`:" type a name"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:bg2("from"),children:$jsx("text",{fg:theme.textMuted,children:"From (\u2191\u2193)"})}),FROMS.map((f)=>{let on=f.id===from2,fg2=on?theme.accent:theme.text;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("from"),children:[$jsx("box",{width:2,children:$jsx("text",{fg:fg2,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:fg2,children:f.label})}),$jsx("text",{fg:theme.textMuted,children:f.hint})]},f.id)}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter create \xB7 Tab next field \xB7 Esc cancel":"type a name"})})]})};extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],HELP_H=4,COL={flexDirection:"column"},mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"open",kind:"select",label:"eikon"},{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"download source",show:(_s,status)=>status.downloadable},{id:"knobsfor",kind:"action",label:"tune",show:(_s,status)=>!!status.path},{id:"reset",kind:"action",label:"reset",show:(_s,status)=>!!status.path},{id:"revert",kind:"action",label:"revert",show:(s)=>s.dirty},{id:"-2",kind:"divider",label:"",show:(_s,status)=>!!status.path},{id:"h-input",kind:"header",label:"input",show:(_s,status)=>!!status.path},{id:"contrast",kind:"tone",label:"contrast",show:(_s,status)=>!!status.path,knob:{kind:"slider",min:0.25,max:4,step:0.05,default:1,hint:"Spread pixel values around their mean. \xD71 = source as-is; higher sharpens, lower flattens. Applied to the image before rasterizing."}},{id:"invert",kind:"tone",label:"invert",show:(_s,status)=>!!status.path,knob:{kind:"toggle",default:!0,hint:"Swap light\u2194dark in the source pixels. On for a light subject on a dark terminal background \u2014 turn off if the subject is darker than its surround."}},{id:"flip",kind:"tone",label:"flip",show:(_s,status)=>!!status.path,knob:{kind:"cycle",options:["none","h","v","hv"],default:"none",hint:"Mirror the source horizontally, vertically, or both before rasterizing."}},{id:"-3",kind:"divider",label:"",show:(_s,status)=>!!status.path}],HELP={open:"Which eikon you're editing. Enter to switch, create a new one, or install from elsewhere.",rasterizer:"The engine that turns your source image/video into text art. Each rasterizer exposes its own look-and-feel settings below the divider.",source:"Pick, generate, or clear source.",fetch:"Download published source for local editing.",knobsfor:"\u2190\u2192 toggles whether the settings below apply to every state or just the one selected in the strip.",reset:"Restore every setting below to this rasterizer's defaults and drop per-state overrides.",submit:"Submit this local eikon after backend preflight.",revert:"Throw away unsaved edits and reload this eikon from disk."},FLIPS=["none","h","v","hv"];function helpOf(row3){if(!row3)return"";if(row3.id==="source")return $jsx($Fragment,{children:$jsx("span",{children:HELP.source})});let head=HELP[row3.id];if(head)return head;if(!row3.knob)return"";if(row3.knob.hint)return row3.knob.hint;if(row3.knob.kind==="cycle")return`\u2190\u2192 or Enter cycles: ${row3.knob.options.join(" \xB7 ")}.`;if(row3.knob.kind==="toggle")return"Space or Enter toggles on/off.";return`\u2190\u2192 or drag adjusts (${row3.knob.min}\u2013${row3.knob.max}); scroll while selected also works.`}function buildRows(r,s,status){let dyn=status.path?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[],head=HEAD2.filter((h2)=>h2.show?h2.show(s,status):!0);return dyn.length?[...head,{id:"h-r",kind:"header",label:r.name},...dyn]:head}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react104.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}function valueOf(s,r,row3,theme,status,peek5,busy){if(row3.id==="open")return`${s.name} \u25B8`;if(row3.id==="rasterizer"){let a=r.available();if(a===!0)return`${r.name} \u25B8`;return $jsxs($Fragment,{children:[$jsx("span",{children:`${r.name} \u25B8`}),$jsx("span",{fg:theme.warning,children:` \u26A0 ${a}`})]})}if(row3.id==="source"){if(!status?.path){if(status?.kind==="downloadable")return"Download source";if(status?.kind==="baked")return"Baked only";return"Missing source"}let d2=s.dims,sz=status.size===void 0?"?":mb2(status.size);return d2?`${basename12(status.path)} \xB7 ${d2.w}\xD7${d2.h} \xB7 ${sz}`:`${basename12(status.path)} \xB7 ${sz}`}if(row3.id==="knobsfor")return`\u25C2 ${!!s.per[s.state]?`${s.state} only`:"all states"} \u25B8`;if(row3.id==="reset")return"\u25B8 defaults";if(row3.id==="revert")return"\u25B8 reload from disk";if(row3.kind==="tone"){if(row3.id==="contrast")return`\xD7${s.tone.contrast.toFixed(2)}`;if(row3.id==="invert")return s.tone.invert?"\u25CF on":"\u25CB off";if(row3.id==="flip")return`\u25C2 ${s.tone.flip} \u25B8`}if(row3.id==="fetch")return busy?"downloading\u2026":peek5?`\u25B8 ${peek5.n} files \xB7 ${mb2(peek5.bytes)}`:"\u25B8 local editable source";if(row3.kind==="knob"&&row3.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row3.id]??row3.knob.default;if(row3.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row3.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row3.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row3,on,dim:dim2}=props,slider=row3.knob?.kind==="slider"?row3.knob:void 0,sval=!slider?0:row3.kind==="tone"?props.s.tone.contrast:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row3.id]??slider.default),pushed=import_react104.useRef(sval);pushed.current=sval;let slide=(v2)=>{if(v2!==pushed.current)props.onSlide?.(v2)};if(row3.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});if(row3.kind==="header")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.textMuted,children:$jsx("u",{children:row3.label})})});let scroll=(e)=>{if(!on||!slider||!props.onWheel)return;e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(-1);if(d2==="down"||d2==="right")props.onWheel(1)};return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,onMouseScroll:scroll,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row3.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:sval,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:slide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row3.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"downloading\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row3,theme,props.status,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme,glyph=useSpinnerGlyph(props.pending.size>0);return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],status=props.stats.get(st),mark2=status.kind==="missing"?"missing":status.kind==="downloadable"?"download":status.role===st?"own src":own?"forked":"",f=props.frames.get(st),gen=props.pending.has(st),empty=!f&&!gen;return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>{if(props.onPick(st),empty)props.onEmpty?.(st)},children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:gen?$jsx("text",{fg:theme.accent,children:`${glyph} gen`}):f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"+"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:st})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:mark2})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),genCaps=null,probeGen=()=>{if(genCaps)return genCaps;let p=exports_eikon_gen.probeCached();return p.catch(()=>{genCaps=null}),genCaps=p};var EikonStudio=import_react104.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),gw=useGateway(),toast=useToast(),wide=useTerminalDimensions().width>=120,ksb=import_react104.useRef(null),outer=import_react104.useRef(null);import_react104.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react104.useState(null),[pane,setPane]=import_react104.useState("knobs"),[sel,setSel]=import_react104.useState(0),[spSel,setSpSel]=import_react104.useState(0),selRef=import_react104.useRef(0);selRef.current=sel;let spRef=import_react104.useRef(0);spRef.current=spSel;let sRef=import_react104.useRef(null);sRef.current=s;let[frames,setFrames]=import_react104.useState([BLANK3]),[tick3,setTick]=import_react104.useState(0),[play,setPlay]=import_react104.useState(!0),[busy,setBusy]=import_react104.useState(!1),[fetching,setFetching]=import_react104.useState(!1),[peek5,setPeek]=import_react104.useState(void 0),[thumbs,setThumbs]=import_react104.useState(new Map),[err,setErr]=import_react104.useState(null),[saving,setSaving]=import_react104.useState(!1),[pending3,setPending]=import_react104.useState(new Set),[genOk,setGenOk]=import_react104.useState(null),frame=frames[tick3%frames.length]??BLANK3,stampRef=import_react104.useRef(""),rev2=import_react104.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),r=import_react104.useMemo(()=>exports_eikon.pick(s?.rasterizer??get2("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps2.ffmpeg,open2=import_react104.useCallback((name)=>{resetCache(),stampRef.current=exports_eikon.sourceStamp(name);let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get2("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src4=exports_eikon.findSource(name,"idle");next2.dims=src4?exports_eikon.probe(src4)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),selRow.current=void 0,setSel(0),setPane("knobs"),setErr(null),setTick(0),setFrames([BLANK3])},[]),tried=import_react104.useRef(!1);import_react104.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open2(props.name||exports_eikon_knobs.slug("new"));let n2=get2("eikon");if(n2)open2(n2)},[open2,props.name]);let dialogRef=import_react104.useRef(dialog);dialogRef.current=dialog,import_react104.useEffect(()=>{if(props.name===void 0)return;let next2=props.name||exports_eikon_knobs.slug("new"),cur=sRef.current;if(cur?.name===next2)return;if(!cur?.dirty)return open2(next2);let dead=!1;return openConfirm(dialogRef.current,{title:"Discard unsaved edits?",danger:!0,body:`Switch to '${next2}' and drop in-memory changes to '${cur.name}'.`}).then((ok)=>{if(!dead&&ok)open2(next2)}),()=>{dead=!0}},[props.name,open2]),import_react104.useEffect(()=>{let dead=!1;return probeGen().then((c)=>{if(!dead)setGenOk(c)}).catch(()=>{}),()=>{dead=!0}},[]);let stats=import_react104.useMemo(()=>{if(!s)return new Map;return new Map(STATES2.map((st)=>[st,exports_eikon.sourceStatus(s.name,st,{sources:s.sources})]))},[s?.name,s?.sources,rev2]),status=s?stats.get(s.state):void 0,src3=status?.path,live=!!src3,baked2=import_react104.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikonFile(p)}catch{return}},[live,s?.name]),url2=status?.sourceUrl;import_react104.useEffect(()=>{if(setPeek(void 0),!url2||!status?.downloadable)return;let dead=!1;return exports_eikon.peekSource(url2).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url2,status?.downloadable]),import_react104.useEffect(()=>{if(!s)return;let stamp2=exports_eikon.sourceStamp(s.name);if(!stampRef.current){stampRef.current=stamp2;return}if(stamp2===stampRef.current)return;if(stampRef.current=stamp2,s.dirty){toast.show({variant:"info",message:"Source changed on disk",duration:3000});return}open2(s.name)},[rev2,s?.name,s?.dirty,open2,toast]);let rows3=import_react104.useMemo(()=>s&&status?buildRows(r,s,status):[],[r,s,status]),navRows=import_react104.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"&&x2.kind!=="header"),[rows3]),selRow=import_react104.useRef(void 0),rid=(x2)=>`${x2.kind}:${x2.id}`,setSelBy=import_react104.useCallback((arg)=>{setSel((prev)=>{let next2=typeof arg==="function"?arg(prev):arg,row3=navRows[next2];return selRow.current=row3?rid(row3):void 0,next2})},[navRows]),prevRows=import_react104.useRef(navRows);import_react104.useEffect(()=>{if(prevRows.current===navRows)return;prevRows.current=navRows;let id=selRow.current;if(!id)return;let ni=navRows.findIndex((x2)=>rid(x2)===id);if(ni>=0&&ni!==selRef.current)setSel(ni)},[navRows]);let kScroll=(ni)=>{let row3=navRows[ni];if(row3)ksb.current?.scrollChildIntoView(`knob-${row3.kind}-${row3.id}`)};import_react104.useEffect(()=>{if(!s)return;if(!src3){let clip=baked2?.states.get(s.state);setFrames(clip?.frames.length?clip.frames:[BLANK3]),setErr(null),setBusy(!1),setTick(0);return}let ctrl=new AbortController;return setBusy(!0),cached2(r,src3,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames),setTick((t2)=>t2%out.frames.length)}),()=>ctrl.abort()},[s?.spatial,s?.tone,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src3,r,baked2]),import_react104.useEffect(()=>{if(!play||!props.focused||frames.length<=1||busy)return;let fps=live?s?.fps??FPS0:baked2?.states.get(s?.state??"idle")?.fps??FPS0,id=setInterval(()=>setTick((t2)=>t2+1),1000/Math.max(1,fps));return()=>clearInterval(id)},[play,props.focused,frames.length,busy,live,s?.fps,s?.state,baked2]),import_react104.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=stats.get(st)?.path;if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2,stats]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react104.useCallback(async()=>{if(!s)return!1;if(!s.dirty)return toast.show({variant:"info",message:"Nothing to save"}),!0;if(!live)return toast.show({variant:"warning",message:"No source \u2014 download or attach before saving"}),!1;setSaving(!0);try{let f=await exports_eikon.save({...s,dirty:!1});return mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename12(f)}`}),!0}catch(e){return toast.error(e instanceof Error?e:Error(String(e))),!1}finally{setSaving(!1)}},[s,live,toast]),doSaveUse=import_react104.useCallback(async()=>{if(!s)return;if(!await doSave())return;exports_eikon.useInstalled(s.name),toast.show({variant:"success",message:`Avatar \u2192 ${s.name}`})},[doSave,s,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},runGenerate=async(st,kind2)=>{if(!s)return;let seed=stats.get("idle")?.path;setPending((prev)=>{let n2=new Set(prev);return n2.add(st),n2});let out=await openGenerate(dialog,exports_eikon_gen.current(),{state:st,kind:kind2,seed,lastPrompt:s.prompts?.[st]});if(!out){setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2});return}let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,out.path,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},prompts:{...p.prompts,[st]:out.prompt},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}finally{setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2})}},download=async()=>{if(!s||fetching)return;setFetching(!0),await exports_eikon.downloadSource(s.name).then((out)=>{if(toast.show({variant:"success",message:`Downloaded ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),sRef.current?.dirty)mutate((prev)=>({...prev,sources:{...out.sources,...prev.sources}}));else open2(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))},doSource=(forSt)=>{if(!s)return;let st=forSt??s.state,info2=stats.get(st)??exports_eikon.sourceStatus(s.name,st,{sources:s.sources}),own=info2.role===st||st==="idle"&&info2.role==="base"||s.sources[st]!==void 0,loc=exports_eikon.localSources(s.name),opts=[...info2.downloadable?[{title:"Download source",value:"download"}]:[],...loc.map((x2)=>({title:x2.file,value:`pick:${x2.file}`,hint:x2.role??"source"})),...genOk?.image?[{title:"Generate image\u2026",value:"gen-image"}]:[],...genOk?.video?[{title:"Generate video\u2026",value:"gen-video"}]:[],{title:"Local file\u2026",value:"local"},...st!=="idle"&&own?[{title:"Same as base",value:"same"}]:[],...own?[{title:"Remove",value:"remove"}]:[]];dialog.replace($jsx(DialogSelect,{title:`Source for '${st}'`,filterable:!1,options:opts,onSelect:async(o)=>{if(o.value==="download"){dialog.clear(),await download();return}if(o.value.startsWith("pick:")){dialog.clear();let file2=o.value.slice(5),role=st==="idle"&&loc.find((x2)=>x2.file===file2)?.role==="base"?"base":st;mutate((prev)=>({...prev,sources:{...prev.sources,[role]:file2},dirty:!0}));return}if(o.value==="local"){let p=await openPathPrompt(dialog,gw,{title:`Source for '${st}'`,label:"png/jpg/webp/gif/mp4/webm/mov \xB7 Tab completes",filter:/\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i});if(!p)return;let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,p,role);mutate((prev)=>({...prev,sources:{...prev.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(o.value==="gen-image")return void runGenerate(st,"image");if(o.value==="gen-video")return void runGenerate(st,"video");dialog.clear(),mutate((prev)=>({...prev,sources:{...prev.sources,[st==="idle"?"base":st]:null},dirty:!0}))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source")return doSource()},switchTo=import_react104.useCallback(async(name)=>{let cur=sRef.current;if(cur?.name===name)return;if(cur?.dirty){if(!await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Open '${name}' and drop in-memory changes to '${cur.name}'.`}))return}open2(name)},[dialog,open2]),apply=import_react104.useCallback(async(res)=>{if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),switchTo(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return switchTo(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[switchTo,toast]),doNew=import_react104.useCallback(async()=>{let res=await openNewEikon(dialog,{});await apply(res)},[dialog,apply]),eikonOptions=import_react104.useCallback(()=>{let installed=exports_eikon.list().map((e)=>({title:e.name,value:e.name,category:"installed",hint:e.hasSource?"\u25CF source":e.sourceUrl?"\u25CB source available":"\u2014"})),seen=new Set(installed.map((o)=>o.value)),bundled=listEikons([BUNDLED_EIKON_DIR,hermesPath("eikons")]).filter((e)=>e.path.startsWith(BUNDLED_EIKON_DIR)).map((e)=>{let slug3=e.meta.name.toLowerCase();return{title:e.meta.name,value:slug3,category:"bundled",hint:`${e.meta.width}\xD7${e.meta.height}`}}).filter((o)=>!seen.has(o.value)),raw2=exports_eikon.raw().filter((n2)=>!seen.has(n2)).map((n2)=>({title:n2,value:n2,category:"installed",hint:"(unsaved)"}));return[...installed,...raw2,...bundled]},[]),doInstall=import_react104.useCallback(async()=>{let src4=await openTextPrompt(dialog,{title:"Inspect eikon source",label:"catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src4)return;let info2;try{info2=await exports_eikon.inspectSource(src4)}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}if(!await openConfirm(dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use Ctrl+U or Gallery after install to select it."].join(`
|
|
4161
|
-
`),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react104.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react104.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path7=submitPath(cur.name);if(publishedInfo(path7)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path7,submit:submit2})},[dialog,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open2(cur.name);return!0}if(pick2==="discard")open2(cur.name);return!0},refresh=import_react104.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open2(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open2,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(key3.eventType==="release")return;if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick3%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","gallery"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),body=$jsxs("box",{position:"relative",flexDirection:"column",width:W2,height:H,flexShrink:0,backgroundColor:theme.background,onMouseScroll:onScroll,onMouseDown:()=>setPlay((p)=>!p),children:[frame.map((ln,i)=>$jsx("text",{fg:err?theme.textMuted:theme.hermAvatar,children:ln},i)),busy&&frames[0]===BLANK3?$jsx("box",{position:"absolute",left:0,top:H>>1,width:W2,justifyContent:"center",children:$jsx(Spinner,{color:theme.textMuted,label:"decoding\u2026"})}):null]}),preview3=$jsxs(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:[!live&&baked2?$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"Baked \u2014 download or attach source to edit."})}):null,spatialOk&&live&&s?$jsxs($Fragment,{children:[$jsx(PanBars,{sp:s.spatial,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar,children:body}),$jsx(SpatialBar,{sp:s.spatial,fps:s.fps,dims:s.dims,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar})]}):body]}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview3}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview3}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react106=__toESM(require_react_production(),1);import{existsSync as existsSync20,readFileSync as readFileSync13}from"fs";import{basename as basename13,dirname as dirname13,join as join17}from"path";var EikonGallery=import_react106.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react106.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),rows3=import_react106.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():basename13(dirname13(e.path)),man=manifest3(dirname13(e.path)),keys2=ids2(man,slug3),mine=meta.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle))},[rev2]),active=usePref("eikon"),path7=import_react106.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path7===row3.path,[sel,setSel]=import_react106.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i);import_react106.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react106.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react106.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;let path8=submitPath(cur.slug);if(publishedInfo(path8)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path8,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),body=here?`Removes ${dirname13(cur.path)} and all its sources. This is the active avatar; deleting it will clear the active avatar selection.`:`Removes ${dirname13(cur.path)} and all its sources.`;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})};return useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)}),$jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx(TabShell,{title:`Gallery (${rows3.length})`,focus:props.focused,grow:3,children:$jsx("scrollbox",{ref:galleryFollow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:rows3.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):rows3.map((r,i)=>{let on=i===sel,here=current2(r);return $jsxs("box",{id:galleryFollow.id(i),flexDirection:"row",height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>setSel(i),onMouseDown:()=>{setSel(i),activate(r)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:here?theme.accent:theme.text,children:[here?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.path)})})}),$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:3,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,children:[$jsx("box",{alignItems:"center",justifyContent:"center",flexGrow:1,children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)})]}):null]})})]}),$jsx(HintBar,{pairs:[[keys.print("list.activate"),"use"],["\u2191\u2193","select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit"]]:[],...cur&&!cur.bundled?[["u/s/d","manage"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest3=(dir2)=>{let file2=join17(dir2,"manifest.json");if(!existsSync20(file2))return;try{let raw2=JSON.parse(readFileSync13(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value)=>{try{let url2=new URL(value);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react109=__toESM(require_react_production(),1);var import_react108=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Delete",value:"delete"}]:[]]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react108.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync21,readFileSync as readFileSync14,readdirSync as readdirSync7,writeFileSync as writeFileSync6}from"fs";import{createHash as createHash4}from"crypto";import{basename as basename14,dirname as dirname14,extname as extname4,join as join18}from"path";var DEFAULT_TIMEOUT=5000,DEFAULT_CACHE_LIMIT=24,dec=new TextDecoder;function hash2(data2){return`sha256:${createHash4("sha256").update(data2).digest("hex")}`}function keyIdentity(s){try{let u3=new URL(s);if(u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")return u3.href.replace(/\/?$/,"/")}catch{}return s}function manifestBaseKey(s){try{let u3=new URL(s);if((u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")&&u3.pathname.endsWith("/manifest.json"))return new URL(".",u3).href}catch{}return}function registryKey(man,source){if(man?.kind!=="eikon.package"||typeof man.id!=="string")return;let sourceKey=man.origin?.sourceKey??man.origin?.identityKey;if(sourceKey)return keyIdentity(sourceKey);try{let host=source?new URL(source).host:void 0;if(!host)return;return`registry:${host}:${man.id}${typeof man.version==="string"&&man.version?`@${man.version}`:""}`}catch{return}}function entryKeys(entry2){return[...new Set([entry2.identityKey,entry2.sourceKey].filter(Boolean).map(keyIdentity))]}function keysFor(inst){let keys=new Set,man=inst.manifest,origin2=typeof man?.origin?.source==="string"?man.origin.source:void 0,head=exports_eikon.header(inst.file),src3=typeof head?.source_url==="string"?head.source_url:inst.sourceUrl,registry2=registryKey(man,origin2);if(registry2)keys.add(registry2);if(origin2){keys.add(keyIdentity(origin2));let base2=manifestBaseKey(origin2);if(base2)keys.add(keyIdentity(base2))}if(src3){keys.add(keyIdentity(src3));let base2=manifestBaseKey(src3);if(base2)keys.add(keyIdentity(base2))}return[...keys]}function read(path7){try{let man=JSON.parse(readFileSync14(path7,"utf8"));return obj(man)?man:void 0}catch{return}}function chosen(active,name){return active===name||active==="default"&&name==="nous"}function media(dir2){return existsSync21(dir2)&&readdirSync7(dir2).length>0}function text3(value){return typeof value==="string"&&value?value:void 0}function life(name,man){let origin2=obj(man.origin)?man.origin:{},display2=obj(man.display)?man.display:{},src3=text3(origin2.source),identity2=text3(origin2.identityKey)??text3(origin2.sourceKey)??text3(origin2.packageUrl)??text3(origin2.repo)??src3,title=text3(display2.title)??text3(man.title),author=text3(display2.author)??text3(man.author);return{name,...title?{title}:{},...author?{author}:{},...text3(man.version)?{version:text3(man.version)}:{},source:{kind:text3(origin2.kind)??"default-catalog",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...text3(origin2.repo)?{repo:text3(origin2.repo)}:{},...text3(origin2.selector)?{selector:text3(origin2.selector)}:{},...text3(origin2.catalogRoot)?{catalogRoot:text3(origin2.catalogRoot)}:{},...text3(origin2.sha)?{sha:text3(origin2.sha)}:{},...text3(origin2.packageUrl)?{packageUrl:text3(origin2.packageUrl)}:{}},trust:text3(origin2.trust)??"verified",active:chosen(get2("eikon"),name),removable:!1,updateable:Boolean(src3??text3(origin2.packageUrl)),updateAvailable:!1,dirty:!1,...text3(man.poster)?{poster:text3(man.poster)}:{},...obj(man.compatibility)?{compatibility:man.compatibility}:{},...text3(origin2.at)?{installedAt:text3(origin2.at)}:{}}}function bundled(xs){let names=new Set(xs.map((x2)=>x2.name.toLowerCase()));return listEikons([BUNDLED_EIKON_DIR]).flatMap((e)=>{let man=read(join18(dirname14(e.path),"manifest.json"));if(man?.kind!=="eikon.package")return[];let name=text3(man.name)??e.meta.name.toLowerCase();if(names.has(name.toLowerCase()))return[];let inst={name,file:e.path,source:exports_eikon.sourceDir(name),hasSource:media(exports_eikon.sourceDir(name)),sourceUrl:text3(man.origin?.source)??text3(man.origin?.packageUrl),manifest:man,lifecycle:life(name,man)};return[{...inst,manifest:man,identityKeys:keysFor(inst)}]})}function cacheKey(entry2){return[entry2.identityKey||entry2.sourceKey||entry2.id,entry2.runtimeUrl,entry2.trust?.runtimeDigest,entry2.trust?.runtimeSize].filter(Boolean).join("|")}function blob(url2){return/\/blobs\/sha256\/[^/?#]+/.test(url2)}function artifact(entry2){return entry2}function obj(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}function rawManifest(entry2){let raw2=entry2.raw;return obj(raw2.manifest)?raw2.manifest:void 0}function role(file2){if(file2.role==="source.base")return"base";if(file2.role?.startsWith("source."))return file2.role.slice(7);if(!file2.path)return;return basename14(file2.path,extname4(file2.path)).toLowerCase()||"base"}function sourceEntries2(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([r,rel2])=>[r,rel2]);if(xs.length)return xs;return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}catch(err){if(strict)throw err}return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}function sourceDescriptors2(man){return sourceEntries2(man).length>0}function sourceAvailable2(entry2,inst){return sourceDescriptors2(inst?.manifest)||sourceDescriptors2(rawManifest(entry2))}function trust(entry2){return entry2.trust}function boundTrust(entry2,raw2){let t2=trust(entry2),man=t2.manifestDigest,run=t2.runtimeDigest;if(!man&&!run)return"unverified";if(man&&hash2(raw2)!==man)throw Error(`catalog trust mismatch: manifest digest for ${entry2.name}`);let pkg=JSON.parse(dec.decode(raw2)),rel2=pkg.entrypoints?.default,got=rel2?pkg.files?.find((f)=>f.path===rel2)?.digest:void 0;if(run&&got!==run)throw Error(`catalog trust mismatch: runtime digest for ${entry2.name}`);return man&&run?"verified":"unverified"}function spec2(man,rel2){return man.files?.find((f)=>f.path===rel2)}async function sourceBytes(man,base2,rel2,opts){let file2=spec2(man,rel2);if(!file2?.digest||typeof file2.size!=="number")throw Error(`source descriptor missing digest or size: ${rel2}`);let raw2=await downloadBytes(new URL(rel2,base2).href,opts);if(raw2.length!==file2.size)throw Error(`source size mismatch: ${rel2}`);if(hash2(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}function target(input){return typeof input==="string"?input:input instanceof URL?input.href:input.url}function verifiedCatalogTrust(entry2){let t2=trust(entry2);return typeof t2.manifestDigest==="string"&&t2.manifestDigest.length>0&&typeof t2.runtimeDigest==="string"&&t2.runtimeDigest.length>0}function installed(){let xs=exports_eikon.list().map((inst)=>({...inst,manifest:inst.manifest,identityKeys:keysFor(inst)}));return[...xs,...bundled(xs)]}function match2(entry2,xs){let keys=entryKeys(entry2),exact=xs.find((x2)=>x2.identityKeys.some((k2)=>keys.includes(k2)));if(exact)return{inst:exact,legacy:!1};let named=xs.find((x2)=>x2.name===entry2.name&&x2.identityKeys.length===0);if(named)return{inst:named,legacy:!0};return}function row3(entry2,xs){let usable=match2(entry2,xs),active=usable?chosen(get2("eikon"),usable.inst.name):!1,installed2=Boolean(usable),conflict=!usable&&chosen(get2("eikon"),entry2.name),blocked=entry2.compatibility?.available===!1,mismatch=usable?.inst.lifecycle.trust==="mismatch",installState=mismatch?"mismatch":blocked?"incompatible":active?"active":conflict?"active-name-conflict":!usable?"available":usable.legacy?"legacy-name-match":"installed",lifecycle2=usable?.inst.lifecycle??{name:entry2.name,title:entry2.title,author:entry2.author,version:entry2.version,source:{kind:"default-catalog",identity:entry2.sourceKey,packageUrl:entry2.packageUrl},trust:verifiedCatalogTrust(entry2)?"verified":"unverified",active:!1,removable:!1,updateable:!1,updateAvailable:!1,dirty:!1,...entry2.poster?{poster:entry2.poster}:{},compatibility:entry2.compatibility},available=sourceAvailable2(entry2,usable?.inst);return{entry:entry2,installed:installed2,active,installState,...usable?.inst.file?{installedPath:usable.inst.file,installedName:usable.inst.name}:{},...usable?.inst.manifest?{installedManifest:usable.inst.manifest}:{},lifecycle:lifecycle2,trust:lifecycle2.trust,updateable:lifecycle2.updateable,updateAvailable:lifecycle2.updateAvailable,removable:lifecycle2.removable,sourceIdentity:lifecycle2.source.identity,sourcePresent:usable?.inst.hasSource??!1,sourceAvailable:available,sourceDownloadable:Boolean(usable&&!usable.inst.hasSource&&available),reason:blocked?entry2.compatibility?.reason??"incompatible":mismatch?"trust mismatch":conflict?"install would replace the active avatar backing package":void 0,action:active?"active":installed2?"use":"install"}}function sizes(man){let files=Array.isArray(man.files)?man.files:[],eikon=files.filter((f)=>f.role==="runtime"||f.path===man.entrypoints?.default).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0),source=files.filter((f)=>typeof f.role==="string"&&f.role.startsWith("source")).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0);return{...eikon>0?{eikon}:{},...source>0?{source}:{}}}function abortErr(){return new DOMException("aborted","AbortError")}class MarketplaceService{catalog;fetcher;timeoutMs;previewCacheLimit;concurrency;allowPrivate;activeLoads=0;queue=[];cache=new Map;inFlight=new Map;constructor(catalog2,opts={}){this.catalog=catalog2,this.fetcher=opts.fetcher??fetch,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT,this.previewCacheLimit=opts.previewCacheLimit??DEFAULT_CACHE_LIMIT,this.concurrency=Math.max(1,Math.floor(opts.concurrency??4)),this.allowPrivate=opts.allowPrivate===!0}rows(query=""){let entries2=searchCatalog(this.catalog.entries,query),xs=installed();return entries2.map((e)=>row3(e,xs))}entry(id){let key4=keyIdentity(id);return this.catalog.entries.find((e)=>keyIdentity(e.identityKey)===key4||keyIdentity(e.sourceKey)===key4||e.id===id||e.name===id)}dl(signal,fetcher=this.fetcher){return{allowPrivate:this.allowPrivate,fetcher:(input,init)=>fetcher(input,signal?{...init,signal}:init)}}runtime(entry2,signal){return async(input)=>{let url2=target(input),bound=keyIdentity(url2)===keyIdentity(entry2.runtimeUrl)&&(!!entry2.trust?.runtimeDigest||blob(url2)),raw2=await downloadBytes(url2,{...this.dl(signal),rejectContentEncoding:bound}),buf=raw2.buffer.slice(raw2.byteOffset,raw2.byteOffset+raw2.byteLength);return new Response(buf,{headers:{"content-length":String(raw2.length)}})}}cached(url2,raw2){let key4=keyIdentity(url2);return async(input,init)=>{if(keyIdentity(target(input))===key4)return new Response(raw2.slice(),{headers:{"content-length":String(raw2.length)}});return this.fetcher(input,init)}}async preview(id,opts={}){if(opts.signal?.aborted)throw abortErr();let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let key4=cacheKey(entry2),hit2=this.cache.get(key4);if(hit2!==void 0)return hit2;let active=this.inFlight.get(key4);if(active)return active;let p=this.enqueue(()=>this.loadPreview(entry2,opts)).finally(()=>this.inFlight.delete(key4));return this.inFlight.set(key4,p),p}async packageSizes(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);return sizes(JSON.parse(dec.decode(await downloadBytes(entry2.packageUrl,this.dl()))))}async install(id,opts={}){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);if(entry2.compatibility?.available===!1)throw Error(entry2.compatibility.reason??"eikon is incompatible");if(!match2(entry2,installed())&&chosen(get2("eikon"),entry2.name)&&!opts.confirmActive)throw Error(`Installing '${entry2.name}' will replace the active avatar's backing package. Pass confirmActive to install it.`);let raw2=await downloadBytes(entry2.packageUrl,this.dl()),state2=boundTrust(entry2,raw2),out=await exports_eikon.fetchSource(entry2.packageUrl,{name:entry2.name,media:opts.media===!0,downloader:this.dl(void 0,this.cached(entry2.packageUrl,raw2))}),ef=exports_eikon.file(out.name);if(!existsSync21(ef)){let art=await loadRuntimeArtifact(entry2,this.runtime(entry2),{allowPrivate:this.allowPrivate});await Bun.write(ef,art.bytes),exports_eikon.notifyRevision()}let mf=join18(exports_eikon.dir(out.name),"manifest.json"),man=JSON.parse(readFileSync14(mf,"utf8")),origin2=man.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:{};return writeFileSync6(mf,JSON.stringify({...man,origin:{...origin2,sourceKey:entry2.sourceKey,identityKey:entry2.identityKey,packageUrl:entry2.packageUrl,trust:state2}},null,2)+`
|
|
4162
|
-
`),out}async downloadSource(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let usable=match2(entry2,installed());if(!usable)throw Error(`marketplace: "${entry2.name}" is not installed`);if(!sourceAvailable2(entry2,usable.inst))throw Error(`marketplace: no source media published for "${entry2.name}"`);let raw2=await downloadBytes(entry2.packageUrl,this.dl());boundTrust(entry2,raw2);let man=JSON.parse(dec.decode(raw2)),xs=sourceEntries2(man,!0);if(xs.length===0)throw Error(`marketplace: no source media published for "${entry2.name}"`);let base2=new URL(".",entry2.packageUrl).href,dir2=exports_eikon.ensure(usable.inst.name).source,pairs=await Promise.all(xs.map(async([r,rel2])=>{let data2=await sourceBytes(man,base2,rel2,this.dl());return[r,exports_eikon.sourceName(man,r,rel2),data2]})),sources={};return await Promise.all(pairs.map(async([r,fname,data2])=>{await Bun.write(join18(dir2,fname),data2),sources[r]=fname})),exports_eikon.attachSources(usable.inst.name,sources),{name:usable.inst.name,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}enqueue(run){return new Promise((resolve4,reject)=>{this.queue.push({run,resolve:resolve4,reject}),this.pump()})}pump(){if(this.activeLoads>=this.concurrency)return;let job=this.queue.shift();if(!job)return;this.activeLoads+=1,job.run().then(job.resolve,job.reject).finally(()=>{this.activeLoads-=1,this.pump()})}async loadPreview(entry2,opts){let ctl=new AbortController,timeout=setTimeout(()=>ctl.abort(),opts.timeoutMs??this.timeoutMs),off=()=>ctl.abort();opts.signal?.addEventListener("abort",off,{once:!0});try{let item=artifact(entry2),text4=(await loadRuntimeArtifact(item,this.runtime(item,ctl.signal),{signal:ctl.signal,allowPrivate:this.allowPrivate})).text;this.cache.set(cacheKey(entry2),text4);while(this.cache.size>this.previewCacheLimit)this.cache.delete(this.cache.keys().next().value);return text4}finally{clearTimeout(timeout),opts.signal?.removeEventListener("abort",off)}}}async function load4(opts={}){let query=opts.query??"";try{if(opts.catalog)publicCatalogUrl(opts.catalog,void 0,opts);let cat=await loadCatalog(opts.catalog,opts.fetcher??fetch,opts),service=new MarketplaceService(cat,opts),rows3=service.rows(query);return{status:rows3.length>0?"ready":"empty",query,rows:rows3,selected:rows3[0],service}}catch(err){return{status:"error",query,rows:[],error:err instanceof Error?err.message:String(err)}}}var NO_MARKET={status:"empty",query:"",rows:[]};function localCatalog(raw2){if(!raw2)return!1;try{let url2=new URL(raw2),host=url2.hostname.toLowerCase().replace(/^\[|\]$/g,"");return url2.protocol==="file:"||host==="localhost"||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host.endsWith(".localhost")}catch{return!1}}var EikonMarketplace=import_react109.memo((props)=>{let toast=useToast(),dialog=useDialog(),keys=useKeys(),rev2=import_react109.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),[sel,setSel]=import_react109.useState(0),[searching,setSearching]=import_react109.useState(!1),[query,setQuery]=import_react109.useState(""),[state2,setState2]=import_react109.useState(NO_MARKET),[loading,setLoading]=import_react109.useState(!1),[installing,setInstalling]=import_react109.useState(!1),[previewState,setPreviewState]=import_react109.useState("idle"),[detailPreview,setDetailPreview]=import_react109.useState(void 0),previewSeq=import_react109.useRef(0),follow=useFollow("market",(i)=>state2.rows[i]?.entry.identityKey??i);import_react109.useEffect(()=>{if(sel>=state2.rows.length)setSel(Math.max(0,state2.rows.length-1))},[state2.rows.length,sel]);let selected=state2.rows[sel];import_react109.useEffect(()=>{if(!selected||!state2.service){setDetailPreview(void 0),props.sidebarPreview?.(void 0);return}let id=++previewSeq.current,key4=selected.entry.identityKey;count("market:preview:load"),state2.service.preview(key4).then((text4)=>{if(previewSeq.current!==id)return;let e=parseEikon(text4),st=e.states.has(previewState)?previewState:"idle",preview3={key:`${key4}:${st}`,eikon:e,state:st,title:selected.entry.name,subtitle:selected.entry.author??"unknown",body:selected.entry.description??"No description.",rows:[{label:"Status",value:previewStatus(selected),block:!0},{label:"Source",value:sourceText(selected),block:!0},{label:"Compat",value:compatText(selected)},{label:"State",value:st},{label:"Digest",value:digest2(selected)??"unknown",block:!0}],states:[...e.states.keys()],onState:setPreviewState};if(props.sidebarPreview)props.sidebarPreview(preview3);setDetailPreview(preview3),count("market:preview:ready")}).catch(()=>{if(previewSeq.current!==id)return;setDetailPreview(void 0),props.sidebarPreview?.(void 0),count("market:preview:error")})},[selected,state2.service,previewState,props.sidebarPreview,props.sidebarHidden]),import_react109.useEffect(()=>()=>{previewSeq.current++,setDetailPreview(void 0),props.sidebarPreview?.(void 0)},[props.sidebarPreview]);let loadMarket=import_react109.useCallback((q5=query)=>{setLoading(!0);let end=mark("market:list:load"),catalog2=process.env.EIKON_URL;load4({catalog:catalog2,allowPrivate:localCatalog(catalog2),query:q5}).then((next2)=>{count("market:list:rows",next2.rows.length),setState2(next2),setSel((p)=>Math.max(0,Math.min(next2.rows.length-1,p)))}).finally(()=>{end(),setLoading(!1)})},[query]),refreshMarket=import_react109.useCallback((svc,q5=query)=>{let rows3=svc.rows(q5);setState2({status:rows3.length>0?"ready":"empty",query:q5,rows:rows3,selected:rows3[0],service:svc}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))},[query]);import_react109.useEffect(()=>{loadMarket(query)},[query,rev2,loadMarket]);let clearPreview=import_react109.useCallback(()=>{previewSeq.current++,props.sidebarPreview?.(void 0),setDetailPreview(void 0)},[props.sidebarPreview]),primary=import_react109.useCallback((idx)=>{let row4=state2.rows[idx??sel],svc=state2.service;if(!row4||!svc||installing)return;(async()=>{let sizes2=!row4.installed?await svc.packageSizes(row4.entry.identityKey).catch(()=>{return}):void 0,pick2=await openEikonMarketplaceAction(dialog,{row:row4,sizes:sizes2});if(!pick2)return;if(pick2==="use"){let name=row4.installedName??row4.entry.name;exports_eikon.useInstalled(name),toast.show({variant:"success",message:`Avatar \u2192 ${name}`}),refreshMarket(svc,query);return}if(pick2==="delete")return removeSelected(idx);setInstalling(!0);try{if(!(row4.installState==="active-name-conflict"?await openConfirm(dialog,{title:`Replace active '${row4.entry.name}'?`,danger:!0,body:`Installing this marketplace package will replace the active avatar's backing package for '${row4.entry.name}' because another package with the same installed name is active.`,yes:"replace active",no:"cancel"}):!0))return;let out=pick2==="download"?await svc.downloadSource(row4.entry.identityKey):await svc.install(row4.entry.identityKey,{media:pick2==="source",confirmActive:row4.installState==="active-name-conflict"});toast.show({variant:"success",message:pick2==="download"?`Downloaded source for '${out.name}'`:`Installed '${out.name}' (${out.n} files)`}),refreshMarket(svc,query)}catch(err){toast.show({variant:"error",title:pick2==="download"?"Source download failed":"Install failed",message:err instanceof Error?err.message:String(err),duration:6000}),refreshMarket(svc,query)}finally{setInstalling(!1)}})()},[dialog,state2.rows,state2.service,sel,installing,toast,refreshMarket,query]),removeSelected=import_react109.useCallback(async(idx)=>{let row4=state2.rows[idx??sel],svc=state2.service,name=row4?.installedName??row4?.entry.name;if(!row4||!svc||!name||!row4.removable)return toast.show({variant:"warning",message:"This eikon is not removable"});let active=row4.active;if(!await openConfirm(dialog,{title:`Remove '${name}'?`,danger:!0,body:active?`Remove the local package for '${name}'. This is the active avatar; removal will clear the active avatar selection.`:`Remove the local package for '${name}'. This does not change the active avatar.`,yes:"remove",no:"cancel"}))return;let out=exports_eikon.remove(name,{confirmActive:active});if(out)return toast.show({variant:"warning",message:out.message});toast.show({variant:"info",message:`Removed '${name}'`}),refreshMarket(svc,query)},[dialog,query,refreshMarket,sel,state2.rows,state2.service,toast]);useKeyboard((key4)=>{if(!props.focused||dialog.open())return;if(searching){if(key4.name==="escape"){setSearching(!1);return}if(key4.name==="backspace"){setQuery((q5)=>q5.slice(0,-1)),setSel(0);return}if(key4.raw&&key4.raw.length===1&&key4.raw>=" "){setQuery((q5)=>q5+key4.raw),setSel(0);return}return}if(key4.name==="escape")return clearPreview();let plain=!key4.shift&&!key4.ctrl&&!key4.meta,move=(by)=>setSel((p)=>{let n=Math.max(0,Math.min(state2.rows.length-1,p+by));return follow.opts.scrollTo?.(n),n});if(plain&&key4.name==="left"){move(-1);return}if(plain&&key4.name==="right"){move(1);return}if(plain&&key4.name==="up"){move(-2);return}if(plain&&key4.name==="down"){move(2);return}if(handleListKey(keys,key4,{count:state2.rows.length,setSel,...follow.opts,onActivate:primary,onToggle:()=>setPreviewState((s)=>s==="idle"?"thinking":"idle"),onSearch:()=>setSearching(!0),onRefresh:()=>loadMarket(query),onDelete:()=>void removeSelected()}))return}),count("market:render");let fallback=props.sidebarHidden||!props.sidebarPreview;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(TabShell,{title:`Marketplace (${state2.rows.length})${searching?` Search: ${query}`:""}`,focus:props.focused,grow:fallback?3:1,children:$jsx(MarketplaceGrid,{rows:state2.rows,sel,follow,loading,error:state2.error,onSel:setSel,onUse:primary})}),fallback?$jsx(TabShell,{title:selected?`Details \u2014 ${selected.entry.name}`:"Details",grow:2,children:$jsx(MarketplaceDetail,{row:selected,loading,installing,onUse:()=>primary(),onState:setPreviewState,preview:detailPreview})}):null]}),$jsx(HintBar,{pairs:[[keys.print("list.activate"),"actions"],["\u2191\u2193\u2190\u2192/Pg","select"],[keys.print("list.search"),searching?"typing search":"search"],[keys.print("list.refresh"),"reload"],["d","delete in modal"],["Space","preview"]]})]})}),MarketplaceGrid=(props)=>{let theme=useTheme().theme;if(props.error)return $jsx("box",{padding:1,children:$jsxs("text",{fg:theme.error,wrapMode:"word",children:["Marketplace unavailable: ",props.error]})},"error");if(props.loading&&props.rows.length===0)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:"Loading shared eikons\u2026"})},"loading");if(props.rows.length===0)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:"No shared eikons match. Press / to change search."})},"empty");return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,verticalScrollbarOptions:VBAR,children:chunk(props.rows,2).map((rows3,y2)=>{let h2=Math.max(...rows3.map(cardHeight));return $jsx("box",{flexDirection:"row",height:h2,flexShrink:0,width:"100%",children:rows3.map((r,x2)=>{let i=y2*2+x2,on=i===props.sel,lines3=posterLines(r.entry.poster);return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:h2,width:"50%",paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:lines3.length,overflow:"hidden",flexDirection:"column",children:lines3.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.entry.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.entry.author??"unknown"," \xB7 ",stateLabel(r,!0)]})})]},r.entry.identityKey)})},y2)})},"rows")},posterLines=(poster2)=>{let lines3=poster2?poster2.split(`
|
|
4163
|
-
`):[];return lines3.length?lines3:["(no poster)"]},cardHeight=(row4)=>posterLines(row4.entry.poster).length+2,chunk=(rows3,n)=>rows3.reduce((acc2,row4,i)=>{if(i%n===0)acc2.push([]);return acc2[acc2.length-1].push(row4),acc2},[]),MarketplaceDetail=(props)=>{let theme=useTheme().theme,r=props.row;if(!r)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:props.loading?"Loading shared eikons\u2026":"No marketplace entry selected."})});let previewState=props.preview?.state??"idle",states=props.preview?[...props.preview.eikon.states.keys()]:[previewState];return $jsxs("box",{flexDirection:"column",padding:1,gap:1,children:[props.preview?$jsx("box",{alignItems:"center",justifyContent:"center",height:8,overflow:"hidden",children:$jsx("box",{flexDirection:"column",children:props.preview.eikon.states.get(props.preview.state)?.frames[0]?.map((line4,i)=>$jsx("text",{children:line4},i))})}):null,$jsx("text",{fg:r.active?theme.accent:theme.text,children:$jsxs("strong",{children:[r.active?"\u25CF ":"",r.entry.name]})}),$jsxs("text",{fg:theme.textMuted,children:["by ",r.entry.author??"unknown"]}),$jsx("text",{fg:theme.text,wrapMode:"word",children:r.entry.description??"No description."}),$jsx("box",{flexDirection:"row",height:1,children:states.map((s,i)=>$jsx(FilterChip,{label:s,state:s===previewState?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.textMuted,onMouseDown:()=>props.onState(s)},s))}),$jsx(DetailRow2,{label:"Status",value:stateLabel(r),block:!0}),$jsx(DetailRow2,{label:"Trust",value:trustLabel(r),block:!0}),$jsx(DetailRow2,{label:"Source",value:sourceText(r),block:!0}),$jsx(DetailRow2,{label:"Compat",value:compatText(r)}),$jsx(DetailRow2,{label:"Digest",value:digest2(r)??"unknown",block:!0}),$jsx("box",{height:1,onMouseDown:props.onUse,children:$jsx("text",{fg:r.action==="active"?theme.textMuted:theme.primary,children:props.installing?"Installing\u2026":"Open actions"})})]})},DetailRow2=(props)=>{let theme=useTheme().theme;if(props.block)return $jsxs("box",{flexDirection:"column",minHeight:2,children:[$jsx("text",{fg:theme.textMuted,children:props.label}),$jsx("text",{fg:theme.text,wrapMode:"word",children:props.value})]});return $jsxs("text",{fg:theme.textMuted,children:[props.label,": ",props.value]})},shortDigest=(value)=>{if(!value)return;let[algo,hash3]=value.includes(":")?value.split(":",2):[void 0,value];if(!hash3||hash3.length<=16)return value;return algo?`${algo}:${hash3.slice(0,12)}\u2026`:`${hash3.slice(0,12)}\u2026`},digest2=(row4)=>{let t2=row4.entry.trust;return shortDigest(t2.manifestDigest??t2.runtimeDigest??t2.digest)},trustLabel=(row4)=>{let t2=row4.trust==="mismatch"?"Mismatch":row4.trust==="verified"?"Verified":row4.trust==="unverified"?"Unverified":"Trust unknown";return row4.reason&&row4.trust==="mismatch"?`${t2}: ${row4.reason}`:t2},previewStatus=(row4)=>{let base2=row4.installState==="active-name-conflict"?"active name conflict":row4.active?"active":row4.installed?"installed":"not installed",src3=row4.sourcePresent?" \xB7 source present":row4.sourceAvailable?" \xB7 source available":"",rm=row4.removable?" \xB7 removable":row4.installed?" \xB7 not removable":"";return`${base2}${src3}${rm}`},sourceText=(row4)=>row4.sourceIdentity??row4.lifecycle.source.packageUrl??row4.entry.sourceKey??row4.entry.packageUrl,compatText=(row4)=>row4.installState==="incompatible"?`Blocked: ${row4.reason??"requires newer Herm/eikon"}`:row4.installState==="active-name-conflict"?`Requires confirmation: ${row4.reason}`:"Compatible",stateLabel=(row4,short2=!1)=>{let base2=row4.installState==="active-name-conflict"?"active name conflict":row4.active?"active":row4.installed?"installed":"not installed";if(short2)return base2;let src3=row4.sourcePresent?" \xB7 source present":row4.sourceDownloadable?" \xB7 source downloadable":row4.sourceAvailable?" \xB7 source available":"",rm=row4.removable?" \xB7 removable":row4.installed?" \xB7 not removable":"";return`${base2}${src3}${rm}`};var EikonGroup=import_react111.memo((props)=>{let labels=SUB_TABS[EIKON_TAB],[target2,setTarget]=import_react111.useState(void 0);import_react111.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]),import_react111.useEffect(()=>{if(props.sub!==2)props.sidebarPreview?.(void 0)},[props.sub,props.sidebarPreview]);let edit2=import_react111.useCallback((name)=>{setTarget(name),props.setSub(1)},[props]),hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:[$jsx(Pane4,{visible:props.sub===0,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===0,onEdit:edit2})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===1,name:target2})}),$jsx(Pane4,{visible:props.sub===2,children:$jsx(EikonMarketplace,{focused:!!props.focused&&props.sub===2,sidebarPreview:props.sidebarPreview,sidebarHidden:props.sidebarHidden})})]})]})}),Pane4=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react112=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync15}from"fs";import{join as join19}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache5=null;function loadTips(){if(cache5)return cache5;try{let body=readFileSync15(join19(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line4 of body.split(`
|
|
4164
|
-
`)){let m2=line4.match(/^\s+"((?:[^"\\]|\\.)*)",?\s*$/);if(m2)tips.push(m2[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"))}cache5=tips.length>10?tips:FALLBACK}catch{cache5=FALLBACK}return cache5}function randomTip(prev){let t2=loadTips();if(t2.length<2)return t2[0]??"";let pick2=t2[Math.floor(Math.random()*t2.length)];while(pick2===prev)pick2=t2[Math.floor(Math.random()*t2.length)];return pick2}import{readFileSync as readFileSync16,existsSync as
|
|
4161
|
+
`).pop();if(!last3)return{err:"no output"};let j2;try{j2=JSON.parse(last3)}catch{return{err:`unparseable: ${last3.slice(0,200)}`}}if(j2.success===!1||j2.error)return{err:String(j2.error??"provider error")};let ref=j2.image??j2.video;if(!ref)return{err:"provider returned no asset"};if(ref.startsWith("/")||ref.startsWith("file://"))return{path:ref.replace(/^file:\/\//,"")};if(/^https?:\/\//.test(ref))return fetchTo(ref,kind2==="image"?".png":".mp4").then((p)=>({path:p})).catch((e)=>({err:`download: ${e instanceof Error?e.message:e}`}));return{err:`unrecognized asset ref: ${ref.slice(0,80)}`}},impl=generate,probeImpl=probe2,current=()=>impl,setImpl=(fn)=>{impl=fn??generate},setProbe=(fn)=>{probeImpl=fn??probe2},probeCached=()=>probeImpl();var import_react102=__toESM(require_react_production(),1);var ORDER4=["name","from"],FROMS=[{id:"blank",label:"blank",hint:"author in Studio"},{id:"file",label:"local file",hint:"png / jpg / webp / gif / mp4"},{id:"install",label:"inspect/install",hint:"catalog name \xB7 github.com/u/r/name \xB7 local dir"}],INSTALL_HINT="catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir";function openNewEikon(dialog,opts={}){return new Promise((resolve4)=>{let chained=!1;dialog.replace($jsx(Form4,{initial:opts.initial,dialog,onChain:()=>{chained=!0},done:(r)=>{chained=!0,dialog.clear(),resolve4(r)}}),()=>{if(!chained)resolve4(null)})})}var Form4=(props)=>{let theme=useTheme().theme,[name,setName]=import_react102.useState(props.initial??""),[from2,setFrom]=import_react102.useState("blank"),[field,setField]=import_react102.useState("name"),slug3=name?exports_eikon_knobs.slug(name):"",ok=slug3.length>0,submit3=async()=>{if(!ok)return;if(from2==="blank")return props.done({name:slug3,from:"blank"});if(props.onChain(),from2==="file"){let file2=await openTextPrompt(props.dialog,{title:"Source file",label:"absolute or ~ path (png / jpg / webp / gif / mp4)"});return props.done(file2?{name:slug3,from:"file",file:file2}:null)}let src3=await openTextPrompt(props.dialog,{title:"Inspect eikon source",label:INSTALL_HINT});if(!src3)return props.done(null);try{let info2=await exports_eikon.inspectSource(src3),ok2=await openConfirm(props.dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use the Library after install to select it."].join(`
|
|
4162
|
+
`),yes:"install",no:"cancel"});return props.done(ok2?{name:slug3,from:"install",src:src3}:null)}catch(e){return await openConfirm(props.dialog,{title:"Inspect failed",danger:!0,body:e instanceof Error?e.message:String(e),yes:"ok",no:"cancel"}),props.done(null)}};useKeyboard((key3)=>{if(key3.name==="escape")return props.done(null);if(key3.name==="tab"){let i=ORDER4.indexOf(field);return setField(ORDER4[(i+(key3.shift?-1:1)+ORDER4.length)%ORDER4.length])}if(key3.name==="return")return void submit3();if(field==="name"){if(key3.name==="backspace")return setName((n)=>n.slice(0,-1));if(key3.raw&&key3.raw.length===1&&/[A-Za-z0-9 _-]/.test(key3.raw))return setName((n)=>n+key3.raw);return}if(key3.name==="up"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.max(0,i-1)].id)}if(key3.name==="down"){let i=FROMS.findIndex((f)=>f.id===from2);return setFrom(FROMS[Math.min(FROMS.length-1,i+1)].id)}});let bg2=(f)=>field===f?theme.backgroundElement:void 0;return $jsxs("box",{flexDirection:"column",width:60,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"New eikon"})})}),$jsx("box",{height:1}),$jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("name"),children:[$jsx("box",{width:9,children:$jsx("text",{fg:theme.textMuted,children:"Name"})}),$jsxs("text",{children:[$jsx("span",{fg:theme.text,children:name}),field==="name"?$jsx("span",{fg:theme.accent,children:"\u2588"}):null]})]}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:slug3?` \u2192 ${slug3}`:" type a name"})}),$jsx("box",{height:1}),$jsx("box",{height:1,backgroundColor:bg2("from"),children:$jsx("text",{fg:theme.textMuted,children:"From (\u2191\u2193)"})}),FROMS.map((f)=>{let on=f.id===from2,fg2=on?theme.accent:theme.text;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:bg2("from"),children:[$jsx("box",{width:2,children:$jsx("text",{fg:fg2,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:fg2,children:f.label})}),$jsx("text",{fg:theme.textMuted,children:f.hint})]},f.id)}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:ok?"Enter create \xB7 Tab next field \xB7 Esc cancel":"type a name"})})]})};extend({slider:SliderRenderable});var PANES=["knobs","preview","strip"],HELP_H=4,COL={flexDirection:"column"},mb2=(n)=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,HEAD2=[{id:"open",kind:"select",label:"eikon"},{id:"rasterizer",kind:"select",label:"rasterizer"},{id:"source",kind:"prompt",label:"source"},{id:"-1",kind:"divider",label:""},{id:"fetch",kind:"action",label:"download source",show:(_s,status)=>status.downloadable},{id:"knobsfor",kind:"action",label:"tune",show:(_s,status)=>!!status.path},{id:"reset",kind:"action",label:"reset",show:(_s,status)=>!!status.path},{id:"revert",kind:"action",label:"revert",show:(s)=>s.dirty},{id:"-2",kind:"divider",label:"",show:(_s,status)=>!!status.path},{id:"h-input",kind:"header",label:"input",show:(_s,status)=>!!status.path},{id:"contrast",kind:"tone",label:"contrast",show:(_s,status)=>!!status.path,knob:{kind:"slider",min:0.25,max:4,step:0.05,default:1,hint:"Spread pixel values around their mean. \xD71 = source as-is; higher sharpens, lower flattens. Applied to the image before rasterizing."}},{id:"invert",kind:"tone",label:"invert",show:(_s,status)=>!!status.path,knob:{kind:"toggle",default:!0,hint:"Swap light\u2194dark in the source pixels. On for a light subject on a dark terminal background \u2014 turn off if the subject is darker than its surround."}},{id:"flip",kind:"tone",label:"flip",show:(_s,status)=>!!status.path,knob:{kind:"cycle",options:["none","h","v","hv"],default:"none",hint:"Mirror the source horizontally, vertically, or both before rasterizing."}},{id:"-3",kind:"divider",label:"",show:(_s,status)=>!!status.path}],HELP={open:"Which eikon you're editing. Enter to switch, create a new one, or install from elsewhere.",rasterizer:"The engine that turns your source image/video into text art. Each rasterizer exposes its own look-and-feel settings below the divider.",source:"Pick, generate, or clear source.",fetch:"Download published source for local editing.",knobsfor:"\u2190\u2192 toggles whether the settings below apply to every state or just the one selected in the strip.",reset:"Restore every setting below to this rasterizer's defaults and drop per-state overrides.",submit:"Submit this local eikon after backend preflight.",revert:"Throw away unsaved edits and reload this eikon from disk."},FLIPS=["none","h","v","hv"];function helpOf(row3){if(!row3)return"";if(row3.id==="source")return $jsx($Fragment,{children:$jsx("span",{children:HELP.source})});let head=HELP[row3.id];if(head)return head;if(!row3.knob)return"";if(row3.knob.hint)return row3.knob.hint;if(row3.knob.kind==="cycle")return`\u2190\u2192 or Enter cycles: ${row3.knob.options.join(" \xB7 ")}.`;if(row3.knob.kind==="toggle")return"Space or Enter toggles on/off.";return`\u2190\u2192 or drag adjusts (${row3.knob.min}\u2013${row3.knob.max}); scroll while selected also works.`}function buildRows(r,s,status){let dyn=status.path?Object.entries(r.knobs).map(([id,def2])=>({id,kind:"knob",label:def2.label??id,knob:def2})):[],head=HEAD2.filter((h2)=>h2.show?h2.show(s,status):!0);return dyn.length?[...head,{id:"h-r",kind:"header",label:r.name},...dyn]:head}var MINI_W=12;function Mini(props){let theme=useTheme().theme,d2=props.dims??{w:1,h:1},ar=d2.w/d2.h,bw=ar>=1?MINI_W:Math.max(4,Math.round(MINI_W*ar)),bh=ar>=1?Math.max(4,Math.round(MINI_W/ar)):MINI_W,short2=Math.min(bw,bh),cw=Math.max(1,short2*props.sp.zoom),cx=(bw-cw)*props.sp.ox,cy=(bh-cw)*props.sp.oy,on=(x2,y2)=>x2>=cx&&x2<cx+cw&&y2>=cy&&y2<cy+cw,cell=(x2,ty)=>{let up=on(x2,ty*2),dn=on(x2,ty*2+1);return up&&dn?"\u2588":up?"\u2580":dn?"\u2584":"\xB7"};return $jsx("box",{flexDirection:"column",flexShrink:0,backgroundColor:theme.backgroundElement,children:Array.from({length:Math.ceil(bh/2)},(_2,ty)=>$jsx("text",{fg:theme.textMuted,children:Array.from({length:bw},(_3,x2)=>cell(x2,ty)).join("")},ty))})}var SP_ROWS=["pan x","pan y","zoom","fps"];function PanBars(props){let theme=useTheme().theme,z2=props.sp.zoom,slack=1-z2,on=(i)=>props.focused&&props.sel===i,fg2=(i)=>on(i)?theme.accent:theme.textMuted,wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(k2,-1);if(d2==="down"||d2==="right")props.onWheel(k2,1)},drag=import_react104.useRef(null),grab=(k2,at)=>{drag.current={at,v:props.sp[k2],k:k2}},scrub=(at,L2)=>{let d2=drag.current;if(!d2||slack<=0)return;props.onSet(d2.k,Math.max(0,Math.min(1,+(d2.v+(at-d2.at)/(slack*L2)).toFixed(3))))},drop=()=>{drag.current=null},tw=Math.max(1,Math.round(z2*W2)),tl=Math.min(W2-tw,Math.round(props.sp.ox*slack*W2)),hbar=" ".repeat(tl)+"\u2588".repeat(tw)+" ".repeat(W2-tl-tw),vh=H*2,th=Math.max(1,z2*vh),ty=props.sp.oy*slack*vh,vbar=Array.from({length:H},(_2,y2)=>{let up=y2*2>=ty&&y2*2<ty+th,dn=y2*2+1>=ty&&y2*2+1<ty+th;return up&&dn?"\u2588\u2588":up?"\u2580\u2580":dn?"\u2584\u2584":" "});return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.children,$jsx("box",{width:W2,height:1,backgroundColor:theme.border,onMouseMove:()=>props.onHover(0),onMouseScroll:wheel("ox"),onMouseDown:(e)=>grab("ox",e.x),onMouseDrag:(e)=>scrub(e.x,W2),onMouseUp:drop,onMouseDragEnd:drop,children:$jsx("text",{fg:fg2(0),children:hbar})})]}),$jsx("box",{flexDirection:"column",width:2,height:H,backgroundColor:theme.border,onMouseMove:()=>props.onHover(1),onMouseScroll:wheel("oy"),onMouseDown:(e)=>grab("oy",e.y),onMouseDrag:(e)=>scrub(e.y,H),onMouseUp:drop,onMouseDragEnd:drop,children:vbar.map((g,y2)=>$jsx("text",{fg:fg2(1),children:g},y2))})]})}function SpatialBar(props){let theme=useTheme().theme,rows3=[{label:"zoom",k:"zoom",min:0.1,max:1,v:props.sp.zoom,i:2},{label:"fps",k:"fps",min:4,max:30,v:props.fps,i:3}],wheel=(k2)=>(e)=>{e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up")props.onWheel(k2,-1);if(d2==="down")props.onWheel(k2,1)};return $jsxs("box",{flexDirection:"row",marginTop:1,flexShrink:0,children:[$jsx("box",{flexDirection:"column",gap:1,flexShrink:0,children:rows3.map((d2)=>{let on=props.focused&&d2.i===props.sel;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onHover(d2.i),onMouseScroll:wheel(d2.k),children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:d2.label})}),$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:d2.min,max:d2.max,value:d2.v,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:(v2)=>props.onSet(d2.k,d2.k==="fps"?Math.round(v2):+v2.toFixed(3))})}),$jsx("box",{width:7,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:` ${d2.k==="fps"?d2.v.toFixed(0):d2.v.toFixed(2)}`})})]},d2.label)})}),$jsx("box",{width:2}),$jsx(Mini,{sp:props.sp,dims:props.dims})]})}function valueOf(s,r,row3,theme,status,peek5,busy){if(row3.id==="open")return`${s.name} \u25B8`;if(row3.id==="rasterizer"){let a=r.available();if(a===!0)return`${r.name} \u25B8`;return $jsxs($Fragment,{children:[$jsx("span",{children:`${r.name} \u25B8`}),$jsx("span",{fg:theme.warning,children:` \u26A0 ${a}`})]})}if(row3.id==="source"){if(!status?.path){if(status?.kind==="downloadable")return"Download source";if(status?.kind==="baked")return"Baked only";return"Missing source"}let d2=s.dims,sz=status.size===void 0?"?":mb2(status.size);return d2?`${basename13(status.path)} \xB7 ${d2.w}\xD7${d2.h} \xB7 ${sz}`:`${basename13(status.path)} \xB7 ${sz}`}if(row3.id==="knobsfor")return`\u25C2 ${!!s.per[s.state]?`${s.state} only`:"all states"} \u25B8`;if(row3.id==="reset")return"\u25B8 defaults";if(row3.id==="revert")return"\u25B8 reload from disk";if(row3.kind==="tone"){if(row3.id==="contrast")return`\xD7${s.tone.contrast.toFixed(2)}`;if(row3.id==="invert")return s.tone.invert?"\u25CF on":"\u25CB off";if(row3.id==="flip")return`\u25C2 ${s.tone.flip} \u25B8`}if(row3.id==="fetch")return busy?"downloading\u2026":peek5?`\u25B8 ${peek5.n} files \xB7 ${mb2(peek5.bytes)}`:"\u25B8 local editable source";if(row3.kind==="knob"&&row3.knob){let k2=exports_eikon_knobs.eff(s,s.state)[row3.id]??row3.knob.default;if(row3.knob.kind==="cycle")return`\u25C2 ${String(k2)} \u25B8`;if(row3.knob.kind==="toggle")return k2?"\u25CF on":"\u25CB off";if(row3.knob.kind==="slider")return Number(k2).toFixed(2)}return""}function KnobRow(props){let theme=useTheme().theme,{row:row3,on,dim:dim2}=props,slider=row3.knob?.kind==="slider"?row3.knob:void 0,sval=!slider?0:row3.kind==="tone"?props.s.tone.contrast:Number(exports_eikon_knobs.eff(props.s,props.s.state)[row3.id]??slider.default),pushed=import_react104.useRef(sval);pushed.current=sval;let slide=(v2)=>{if(v2!==pushed.current)props.onSlide?.(v2)};if(row3.kind==="divider")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.border,children:"\u2500".repeat(24)})});if(row3.kind==="header")return $jsx("box",{id:props.id,height:1,children:$jsx("text",{fg:theme.textMuted,children:$jsx("u",{children:row3.label})})});let scroll=(e)=>{if(!on||!slider||!props.onWheel)return;e.stopPropagation();let d2=e.scroll?.direction;if(d2==="up"||d2==="left")props.onWheel(-1);if(d2==="down"||d2==="right")props.onWheel(1)};return $jsxs("box",{id:props.id,height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:props.onHover,onMouseDown:props.onClick,onMouseScroll:scroll,children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{width:14,children:$jsx("text",{fg:dim2?theme.textMuted:on?theme.text:theme.textMuted,children:row3.label})}),slider?$jsxs($Fragment,{children:[$jsx("box",{width:20,height:1,children:$jsx("slider",{orientation:"horizontal",min:slider.min,max:slider.max,value:sval,foregroundColor:on?theme.accent:theme.textMuted,backgroundColor:theme.border,onChange:slide})}),$jsx("box",{width:1})]}):null,$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:props.busy&&row3.id==="fetch"?$jsx(Spinner,{color:theme.accent,label:"downloading\u2026"}):$jsx("text",{fg:dim2?theme.textMuted:theme.text,children:valueOf(props.s,props.r,row3,theme,props.status,props.peek,props.busy)})})]})}function Strip(props){let theme=useTheme().theme,glyph=useSpinnerGlyph(props.pending.size>0);return $jsx("box",{flexDirection:"row",gap:1,children:STATES2.map((st)=>{let on=props.s.state===st,own=!!props.s.per[st],status=props.stats.get(st),mark2=status.kind==="missing"?"missing":status.kind==="downloadable"?"download":status.role===st?"own src":own?"forked":"",f=props.frames.get(st),gen=props.pending.has(st),empty=!f&&!gen;return $jsxs("box",{flexDirection:"column",alignItems:"center",onMouseDown:()=>{if(props.onPick(st),empty)props.onEmpty?.(st)},children:[$jsx("box",{border:!0,borderStyle:"rounded",borderColor:on&&props.focused?theme.primary:on?theme.accent:theme.border,width:18,height:10,overflow:"hidden",alignItems:"center",justifyContent:"center",children:gen?$jsx("text",{fg:theme.accent,children:`${glyph} gen`}):f?f.map((ln,i)=>$jsx("text",{fg:on?theme.text:theme.textMuted,children:ln},i)):$jsx("text",{fg:theme.textMuted,children:"+"})}),$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.accent:theme.textMuted,children:st})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:mark2})})]},st)})})}var BLANK3=Array.from({length:H},()=>" ".repeat(W2)),genCaps=null,probeGen=()=>{if(genCaps)return genCaps;let p=exports_eikon_gen.probeCached();return p.catch(()=>{genCaps=null}),genCaps=p};var EikonStudio=import_react104.memo((props)=>{let theme=useTheme().theme,keys=useKeys(),dialog=useDialog(),gw=useGateway(),toast=useToast(),wide=useTerminalDimensions().width>=120,ksb=import_react104.useRef(null),outer=import_react104.useRef(null);import_react104.useSyncExternalStore(exports_eikon.onRegistry,()=>exports_eikon.rasterizers().length);let[s,setS]=import_react104.useState(null),[pane,setPane]=import_react104.useState("knobs"),[sel,setSel]=import_react104.useState(0),[spSel,setSpSel]=import_react104.useState(0),selRef=import_react104.useRef(0);selRef.current=sel;let spRef=import_react104.useRef(0);spRef.current=spSel;let sRef=import_react104.useRef(null);sRef.current=s;let[frames,setFrames]=import_react104.useState([BLANK3]),[tick3,setTick]=import_react104.useState(0),[play,setPlay]=import_react104.useState(!0),[busy,setBusy]=import_react104.useState(!1),[fetching,setFetching]=import_react104.useState(!1),[peek5,setPeek]=import_react104.useState(void 0),[thumbs,setThumbs]=import_react104.useState(new Map),[err,setErr]=import_react104.useState(null),[saving,setSaving]=import_react104.useState(!1),[pending3,setPending]=import_react104.useState(new Set),[genOk,setGenOk]=import_react104.useState(null),frame=frames[tick3%frames.length]??BLANK3,stampRef=import_react104.useRef(""),rev2=import_react104.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),r=import_react104.useMemo(()=>exports_eikon.pick(s?.rasterizer??get2("eikonRasterizer")),[s?.rasterizer]),spatialOk=caps2.ffmpeg,open2=import_react104.useCallback((name)=>{resetCache(),stampRef.current=exports_eikon.sourceStamp(name);let seed=exports_eikon.readStudio(name),ra=exports_eikon.pick(seed?.rasterizer??get2("eikonRasterizer")),next2=exports_eikon_knobs.fresh(name,ra,seed),src4=exports_eikon.findSource(name,"idle");next2.dims=src4?exports_eikon.probe(src4)??null:null;for(let st of STATES2){let p=exports_eikon.findSource(name,st);if(p)prewarm(p,next2.fps)}setS(next2),selRow.current=void 0,setSel(0),setPane("knobs"),setErr(null),setTick(0),setFrames([BLANK3])},[]),tried=import_react104.useRef(!1);import_react104.useEffect(()=>{if(tried.current)return;if(tried.current=!0,props.name)return open2(props.name||exports_eikon_knobs.slug("new"));let n2=get2("eikon");if(n2)open2(n2)},[open2,props.name]);let dialogRef=import_react104.useRef(dialog);dialogRef.current=dialog,import_react104.useEffect(()=>{if(props.name===void 0)return;let next2=props.name||exports_eikon_knobs.slug("new"),cur=sRef.current;if(cur?.name===next2)return;if(!cur?.dirty)return open2(next2);let dead=!1;return openConfirm(dialogRef.current,{title:"Discard unsaved edits?",danger:!0,body:`Switch to '${next2}' and drop in-memory changes to '${cur.name}'.`}).then((ok)=>{if(!dead&&ok)open2(next2)}),()=>{dead=!0}},[props.name,open2]),import_react104.useEffect(()=>{let dead=!1;return probeGen().then((c)=>{if(!dead)setGenOk(c)}).catch(()=>{}),()=>{dead=!0}},[]);let stats=import_react104.useMemo(()=>{if(!s)return new Map;return new Map(STATES2.map((st)=>[st,exports_eikon.sourceStatus(s.name,st,{sources:s.sources})]))},[s?.name,s?.sources,rev2]),status=s?stats.get(s.state):void 0,src3=status?.path,live=!!src3,baked2=import_react104.useMemo(()=>{if(live||!s)return;let p=exports_eikon.baked(s.name);if(!p)return;try{return exports_eikon.parseEikonFile(p)}catch{return}},[live,s?.name]),url2=status?.sourceUrl;import_react104.useEffect(()=>{if(setPeek(void 0),!url2||!status?.downloadable)return;let dead=!1;return exports_eikon.peekSource(url2).then((x2)=>{if(!dead)setPeek(x2)}),()=>{dead=!0}},[url2,status?.downloadable]),import_react104.useEffect(()=>{if(!s)return;let stamp2=exports_eikon.sourceStamp(s.name);if(!stampRef.current){stampRef.current=stamp2;return}if(stamp2===stampRef.current)return;if(stampRef.current=stamp2,s.dirty){toast.show({variant:"info",message:"Source changed on disk",duration:3000});return}open2(s.name)},[rev2,s?.name,s?.dirty,open2,toast]);let rows3=import_react104.useMemo(()=>s&&status?buildRows(r,s,status):[],[r,s,status]),navRows=import_react104.useMemo(()=>rows3.map((x2,i)=>({...x2,i})).filter((x2)=>x2.kind!=="divider"&&x2.kind!=="header"),[rows3]),selRow=import_react104.useRef(void 0),rid=(x2)=>`${x2.kind}:${x2.id}`,setSelBy=import_react104.useCallback((arg)=>{setSel((prev)=>{let next2=typeof arg==="function"?arg(prev):arg,row3=navRows[next2];return selRow.current=row3?rid(row3):void 0,next2})},[navRows]),prevRows=import_react104.useRef(navRows);import_react104.useEffect(()=>{if(prevRows.current===navRows)return;prevRows.current=navRows;let id=selRow.current;if(!id)return;let ni=navRows.findIndex((x2)=>rid(x2)===id);if(ni>=0&&ni!==selRef.current)setSel(ni)},[navRows]);let kScroll=(ni)=>{let row3=navRows[ni];if(row3)ksb.current?.scrollChildIntoView(`knob-${row3.kind}-${row3.id}`)};import_react104.useEffect(()=>{if(!s)return;if(!src3){let clip=baked2?.states.get(s.state);setFrames(clip?.frames.length?clip.frames:[BLANK3]),setErr(null),setBusy(!1),setTick(0);return}let ctrl=new AbortController;return setBusy(!0),cached2(r,src3,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,s.state),ctrl.signal).then((out)=>{if(ctrl.signal.aborted)return;if(setBusy(!1),"err"in out){setErr(out.err);return}setErr(null),setFrames(out.frames),setTick((t2)=>t2%out.frames.length)}),()=>ctrl.abort()},[s?.spatial,s?.tone,s?.base,s?.per,s?.state,s?.fps,s?.rasterizer,src3,r,baked2]),import_react104.useEffect(()=>{if(!play||!props.focused||frames.length<=1||busy)return;let fps=live?s?.fps??FPS0:baked2?.states.get(s?.state??"idle")?.fps??FPS0,id=setInterval(()=>setTick((t2)=>t2+1),1000/Math.max(1,fps));return()=>clearInterval(id)},[play,props.focused,frames.length,busy,live,s?.fps,s?.state,baked2]),import_react104.useEffect(()=>{if(!s)return;let dead=!1,t2=setTimeout(()=>{if(dead)return;let jobs=STATES2.map((st)=>{let sp=stats.get(st)?.path;if(!sp){let f=baked2?.states.get(st)?.frames[0];return Promise.resolve([st,f?thumb(f):void 0])}return cached2(r,sp,s.spatial,s.tone,s.fps,exports_eikon_knobs.eff(s,st)).then((res)=>[st,"err"in res?void 0:thumb(res.frames[0])])});Promise.all(jobs).then((done)=>{if(dead)return;setThumbs(new Map(done))})},400);return()=>{dead=!0,clearTimeout(t2)}},[frames,s?.per,s?.sources,s?.name,s?.fps,r,baked2,stats]);let mutate=(fn)=>setS((p)=>p?fn(p):p),setSpatial=(sp)=>mutate((p)=>({...p,spatial:{...p.spatial,...sp},dirty:!0})),setBar=(k2,v2)=>k2==="fps"?mutate((p)=>({...p,fps:Math.round(v2),dirty:!0})):setSpatial({[k2]:v2}),stepBar=(k2,d2)=>{let cur=sRef.current;if(!cur)return;if(k2==="fps")return setBar("fps",Math.max(4,Math.min(30,cur.fps+d2*2)));if(k2==="zoom")return setSpatial({zoom:Math.max(0.1,Math.min(1,+(cur.spatial.zoom+d2*0.03).toFixed(3)))});return setSpatial({[k2]:Math.max(0,Math.min(1,+(cur.spatial[k2]+d2*0.03).toFixed(3)))})},doSave=import_react104.useCallback(async()=>{if(!s)return!1;if(!s.dirty)return toast.show({variant:"info",message:"Nothing to save"}),!0;if(!live)return toast.show({variant:"warning",message:"No source \u2014 download or attach before saving"}),!1;setSaving(!0);try{let f=await exports_eikon.save({...s,dirty:!1});return mutate((p)=>({...p,dirty:!1})),toast.show({variant:"success",message:`Saved \u2192 ${basename13(f)}`}),!0}catch(e){return toast.error(e instanceof Error?e:Error(String(e))),!1}finally{setSaving(!1)}},[s,live,toast]),doSaveUse=import_react104.useCallback(async()=>{if(!s)return;if(!await doSave())return;exports_eikon.useInstalled(s.name),toast.show({variant:"success",message:`Avatar \u2192 ${s.name}`})},[doSave,s,toast]),doSelectRasterizer=()=>{let opts=exports_eikon.rasterizers().map((x2)=>{let a=x2.available();return{title:x2.name,value:x2.name,description:Object.keys(x2.knobs).join(" \xB7 "),hint:a===!0?void 0:a}});dialog.replace($jsx(DialogSelect,{title:"Rasterizer",filterable:!1,current:r.name,options:opts,onSelect:(o)=>{dialog.clear();let next2=exports_eikon.rasterizer(o.value);if(!next2)return;let a=next2.available();if(a!==!0)return toast.show({variant:"warning",message:`${o.value}: ${a}`});set("eikonRasterizer",o.value),mutate((p)=>exports_eikon_knobs.swap(p,next2))}}),()=>{})},runGenerate=async(st,kind2)=>{if(!s)return;let seed=stats.get("idle")?.path;setPending((prev)=>{let n2=new Set(prev);return n2.add(st),n2});let out=await openGenerate(dialog,exports_eikon_gen.current(),{state:st,kind:kind2,seed,lastPrompt:s.prompts?.[st]});if(!out){setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2});return}let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,out.path,role);mutate((p)=>({...p,sources:{...p.sources,[role]:f},prompts:{...p.prompts,[st]:out.prompt},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}finally{setPending((prev)=>{let n2=new Set(prev);return n2.delete(st),n2})}},download=async()=>{if(!s||fetching)return;setFetching(!0),await exports_eikon.downloadSource(s.name).then((out)=>{if(toast.show({variant:"success",message:`Downloaded ${out.n} file(s) \xB7 ${mb2(out.bytes)}`}),sRef.current?.dirty)mutate((prev)=>({...prev,sources:{...out.sources,...prev.sources}}));else open2(s.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e)))).finally(()=>setFetching(!1))},doSource=(forSt)=>{if(!s)return;let st=forSt??s.state,info2=stats.get(st)??exports_eikon.sourceStatus(s.name,st,{sources:s.sources}),own=info2.role===st||st==="idle"&&info2.role==="base"||s.sources[st]!==void 0,loc=exports_eikon.localSources(s.name),opts=[...info2.downloadable?[{title:"Download source",value:"download"}]:[],...loc.map((x2)=>({title:x2.file,value:`pick:${x2.file}`,hint:x2.role??"source"})),...genOk?.image?[{title:"Generate image\u2026",value:"gen-image"}]:[],...genOk?.video?[{title:"Generate video\u2026",value:"gen-video"}]:[],{title:"Local file\u2026",value:"local"},...st!=="idle"&&own?[{title:"Same as base",value:"same"}]:[],...own?[{title:"Remove",value:"remove"}]:[]];dialog.replace($jsx(DialogSelect,{title:`Source for '${st}'`,filterable:!1,options:opts,onSelect:async(o)=>{if(o.value==="download"){dialog.clear(),await download();return}if(o.value.startsWith("pick:")){dialog.clear();let file2=o.value.slice(5),role=st==="idle"&&loc.find((x2)=>x2.file===file2)?.role==="base"?"base":st;mutate((prev)=>({...prev,sources:{...prev.sources,[role]:file2},dirty:!0}));return}if(o.value==="local"){let p=await openPathPrompt(dialog,gw,{title:`Source for '${st}'`,label:"png/jpg/webp/gif/mp4/webm/mov \xB7 Tab completes",filter:/\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i});if(!p)return;let role=st==="idle"&&!s.sources.base?"base":st;try{let f=exports_eikon.adopt(s.name,p,role);mutate((prev)=>({...prev,sources:{...prev.sources,[role]:f},dirty:!0}))}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}return}if(o.value==="gen-image")return void runGenerate(st,"image");if(o.value==="gen-video")return void runGenerate(st,"video");dialog.clear(),mutate((prev)=>({...prev,sources:{...prev.sources,[st==="idle"?"base":st]:null},dirty:!0}))}}),()=>{})},doPrompt=async(id)=>{if(!s)return;if(id==="source")return doSource()},switchTo=import_react104.useCallback(async(name)=>{let cur=sRef.current;if(cur?.name===name)return;if(cur?.dirty){if(!await openConfirm(dialog,{title:"Discard unsaved edits?",danger:!0,body:`Open '${name}' and drop in-memory changes to '${cur.name}'.`}))return}open2(name)},[dialog,open2]),apply=import_react104.useCallback(async(res)=>{if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),switchTo(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return switchTo(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[switchTo,toast]),doNew=import_react104.useCallback(async()=>{let res=await openNewEikon(dialog,{});await apply(res)},[dialog,apply]),eikonOptions=import_react104.useCallback(()=>{let installed=exports_eikon.list().map((e)=>({title:e.name,value:e.name,category:"installed",hint:e.hasSource?"\u25CF source":e.sourceUrl?"\u25CB source available":"\u2014"})),seen=new Set(installed.map((o)=>o.value)),bundled=listEikons([BUNDLED_EIKON_DIR,hermesPath("eikons")]).filter((e)=>e.path.startsWith(BUNDLED_EIKON_DIR)).map((e)=>{let slug3=e.meta.name.toLowerCase();return{title:e.meta.name,value:slug3,category:"bundled",hint:`${e.meta.width}\xD7${e.meta.height}`}}).filter((o)=>!seen.has(o.value)),raw2=exports_eikon.raw().filter((n2)=>!seen.has(n2)).map((n2)=>({title:n2,value:n2,category:"installed",hint:"(unsaved)"}));return[...installed,...raw2,...bundled]},[]),doInstall=import_react104.useCallback(async()=>{let src4=await openTextPrompt(dialog,{title:"Inspect eikon source",label:"catalog name \xB7 github.com/u/r/eikon-name \xB7 git URL \xB7 http://\u2026/ \xB7 local dir"});if(!src4)return;let info2;try{info2=await exports_eikon.inspectSource(src4)}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}if(!await openConfirm(dialog,{title:`Install '${info2.title??info2.name}'?`,body:[`Name: ${info2.name}`,`Author: ${info2.author??"unknown"}`,`Version: ${info2.version??"unknown"}`,`Source: ${info2.sourceLabel}`,`Trust: ${info2.trust}${info2.reason?` (${info2.reason})`:""}`,`Preview: ${info2.previewAvailable?"available":"none"}; poster: ${info2.posterAvailable?"available":"none"}`,"Install does not activate; use Ctrl+U or Library after install to select it."].join(`
|
|
4163
|
+
`),yes:"install",no:"cancel"}))return;toast.show({variant:"info",message:`Installing from ${src4}\u2026`}),await exports_eikon.installPackage(src4).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`}),switchTo(out.name)}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,switchTo,toast]),doOpen=import_react104.useCallback(()=>{let cur=sRef.current,opts=[...eikonOptions(),{title:"+ New\u2026",value:"__new",category:""},{title:"+ Install\u2026",value:"__install",category:""}];dialog.replace($jsx(DialogSelect,{title:"Open eikon",current:cur?.name,options:opts,onSelect:(o)=>{if(dialog.clear(),o.value==="__new")return void doNew();if(o.value==="__install")return void doInstall();switchTo(o.value)}}),()=>{})},[dialog,eikonOptions,switchTo,doNew,doInstall]),doSubmit=import_react104.useCallback(async()=>{let cur=sRef.current;if(!cur)return;let path7=submitPath(cur.name);if(publishedInfo(path7)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}if(cur.dirty||!existsSync20(path7)){let pick2=await openSaveDiscard(dialog,{title:"Save before submit?",body:`'${cur.name}' has unsaved changes. Save to submit the current preview, discard to submit the last saved artifact, or keep editing.`});if(pick2==="save"){if(get2("eikon")===cur.name){if(!await openConfirm(dialog,{title:`Save active '${cur.name}' before submit?`,danger:!0,body:"Saving changes the active avatar's backing artifact. Submit itself will not change active selection.",yes:"save",no:"cancel"}))return}if(!await doSave())return}else if(pick2==="discard")open2(cur.name);else return}if(!existsSync20(path7)){toast.show({variant:"warning",message:"Save this eikon before submitting"});return}await openEikonSubmit(dialog,{name:cur.name,path:path7,submit:submit2})},[dialog,doSave,open2,toast]),doAction=async(id)=>{if(!s)return;if(id==="knobsfor")return mutate((p)=>p.per[p.state]?exports_eikon_knobs.unfork(p):exports_eikon_knobs.fork(p));if(id==="submit"){doSubmit();return}if(id==="revert"){discard();return}if(id==="reset"){if(await openConfirm(dialog,{title:"Reset settings?",body:"Restore rasterizer defaults and drop all per-state overrides.",danger:!0}))mutate((p)=>exports_eikon_knobs.reset(p,r));return}if(id==="fetch"){if(!status?.downloadable||fetching)return;await download()}},doStripMenu=()=>{if(!s)return;dialog.replace($jsx(DialogSelect,{title:`State: ${s.state}`,filterable:!1,options:[{title:"Source\u2026",value:"source"},{title:s.per[s.state]?"Clear override (back to base)":"Tune this state only",value:"fork"}],onSelect:(o)=>{if(o.value==="source"){doSource();return}dialog.clear(),mutate(s.per[s.state]?exports_eikon_knobs.unfork:exports_eikon_knobs.fork)}}),()=>{})},setTone=(t2)=>mutate((p)=>({...p,tone:{...p.tone,...t2},dirty:!0})),stepRow=(row3,d2)=>{if(row3.kind==="tone"){if(row3.id==="contrast"){let def2=row3.knob,cur=sRef.current?.tone.contrast??1;return setTone({contrast:+Math.max(def2.min,Math.min(def2.max,cur+d2*def2.step)).toFixed(2)})}if(row3.id==="invert")return setTone({invert:!sRef.current?.tone.invert});if(row3.id==="flip"){let cur=sRef.current?.tone.flip??"none",i=FLIPS.indexOf(cur);return setTone({flip:FLIPS[(i+d2+FLIPS.length)%FLIPS.length]})}return}if(row3.kind!=="knob"||!row3.knob)return;mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.step(k2,row3.id,row3.knob,d2)))},act=(row3,via)=>{if(!row3||!sRef.current)return;if(row3.kind==="select"){if(row3.id==="open")return doOpen();return doSelectRasterizer()}if(row3.kind==="prompt")return void doPrompt(row3.id);if(row3.kind==="action"){if(via==="space"&&row3.id==="reset")return;return void doAction(row3.id)}if(row3.kind==="tone"||row3.kind==="knob"){if(row3.knob.kind==="slider")return;return stepRow(row3,1)}},activate=()=>act(navRows[selRef.current],"enter"),toggle=()=>act(navRows[selRef.current],"space"),adjust=(d2)=>{let row3=navRows[selRef.current];if(!row3)return;if(row3.id==="knobsfor")return void doAction("knobsfor");stepRow(row3,d2)},discard=async()=>{let cur=sRef.current;if(!cur?.dirty)return!1;let pick2=await openSaveDiscard(dialog,{title:"Unsaved edits",body:`'${cur.name}' has unsaved changes. Save them, discard them, or keep editing?`});if(pick2==="save"){if(await doSave())open2(cur.name);return!0}if(pick2==="discard")open2(cur.name);return!0},refresh=import_react104.useCallback(()=>{let cur=sRef.current;if(!cur)return;if(stampRef.current=exports_eikon.sourceStamp(cur.name),cur.dirty){toast.show({variant:"info",message:"Reload skipped: unsaved edits",duration:3000});return}open2(cur.name),toast.show({variant:"info",message:"Reloaded",duration:1000})},[open2,toast]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;if(key3.name==="u"&&key3.ctrl&&sRef.current)return void doSaveUse();if(key3.name==="u"&&sRef.current)return void doSubmit();if(key3.eventType==="release")return;if(keys.match("eikon.save",key3)){if(!saving)doSave();return}if(key3.name==="escape")return void discard();if(key3.name==="tab"){let i=PANES.indexOf(pane),next2=PANES[(i+(key3.shift?PANES.length-1:1))%PANES.length];setPane(next2),outer.current?.scrollChildIntoView(`studio-${next2}`);return}if(!s){if(key3.name==="return")return void doNew();return}if(pane==="knobs"){if(handleListKey(keys,key3,{count:navRows.length,setSel:setSelBy,scrollTo:kScroll,page:Math.max(1,(ksb.current?.viewport.height??10)-1),onActivate:activate,onToggle:toggle,onNew:()=>void doNew(),onRefresh:refresh}))return;if(key3.name==="left")return adjust(-1);if(key3.name==="right")return adjust(1);return}if(pane==="preview"){if(keys.match("list.toggle",key3))return setPlay((p)=>!p);if(!spatialOk||!live)return;if(handleListKey(keys,key3,{count:SP_ROWS.length,setSel:setSpSel}))return;let k2=["ox","oy","zoom","fps"][spRef.current],fine=key3.shift&&k2!=="fps",d2=(name)=>name==="left"?-1:1;if(key3.name==="left"||key3.name==="right"){if(fine&&(k2==="ox"||k2==="oy"||k2==="zoom")){let cur=sRef.current.spatial[k2];return setSpatial({[k2]:Math.max(k2==="zoom"?0.1:0,Math.min(1,+(cur+d2(key3.name)*0.01).toFixed(3)))})}return stepBar(k2,d2(key3.name))}return}if(key3.name==="left")return mutate((p)=>exports_eikon_knobs.cycle(p,-1));if(key3.name==="right")return mutate((p)=>exports_eikon_knobs.cycle(p,1));if(key3.name==="return")return doStripMenu()});let onScroll=(e)=>{if(e.stopPropagation(),!spatialOk||!live||!e.scroll)return;let d2=e.scroll.direction;if(d2!=="up"&&d2!=="down")return;let sign=d2==="up"?-1:1;if(e.modifiers.ctrl)return mutate((p)=>({...p,spatial:exports_eikon_knobs.zoom(p.spatial,sign),dirty:!0}));if(e.modifiers.shift)return mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,sign,0),dirty:!0}));mutate((p)=>({...p,spatial:exports_eikon_knobs.pan(p.spatial,0,sign),dirty:!0}))},n=frames.length,title=s?`Preview \u2014 ${s.state}${s.per[s.state]?" (forked)":""}`+(n>1?` \xB7 ${play?"\u25B6":"\u23F8"} ${tick3%n+1}/${n}`:"")+(live?"":baked2?" \xB7 (baked)":""):"Preview",previewErr=err??(!s||src3||baked2?null:url2?"no source \u2014 Enter on 'download source'":"no source \u2014 Enter on 'source'"),hint=!s?[["Enter","new eikon"],["Shift+\u2192","library"]]:pane==="knobs"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.activate"),"edit"],[keys.print("list.refresh"),"reload"],[keys.print("list.new"),"new"],["u","submit"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:pane==="preview"?[["\u2191\u2193","row"],["\u2190\u2192","adjust"],[keys.print("list.toggle"),"play/pause"],["wheel","pan"],["Ctrl+wheel","zoom"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]]:[["\u2190\u2192","state"],[keys.print("list.activate"),"actions"],[keys.print("eikon.save"),"save"],["Ctrl+U","save & use"],["Tab","pane"]],BAR_H=spatialOk&&live?Math.max(Math.ceil(MINI_W/2),3)+1:0,PREVIEW_W=Math.max(W2+2,38+MINI_W)+6,PREVIEW_H=H+(spatialOk&&live?1:0)+BAR_H+6+(previewErr?1:0),body=$jsxs("box",{position:"relative",flexDirection:"column",width:W2,height:H,flexShrink:0,backgroundColor:theme.background,onMouseScroll:onScroll,onMouseDown:()=>setPlay((p)=>!p),children:[frame.map((ln,i)=>$jsx("text",{fg:err?theme.textMuted:theme.hermAvatar,children:ln},i)),busy&&frames[0]===BLANK3?$jsx("box",{position:"absolute",left:0,top:H>>1,width:W2,justifyContent:"center",children:$jsx(Spinner,{color:theme.textMuted,label:"decoding\u2026"})}):null]}),preview2=$jsxs(TabShell,{title:spatialOk?title:`${title} \xB7 (ffmpeg not installed)`,error:previewErr,focus:pane==="preview",children:[!live&&baked2?$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"Baked \u2014 download or attach source to edit."})}):null,spatialOk&&live&&s?$jsxs($Fragment,{children:[$jsx(PanBars,{sp:s.spatial,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar,children:body}),$jsx(SpatialBar,{sp:s.spatial,fps:s.fps,dims:s.dims,sel:spSel,focused:pane==="preview",onHover:(i)=>{setPane("preview"),setSpSel(i)},onSet:setBar,onWheel:stepBar})]}):body]}),help=helpOf(navRows[sel]),panel=$jsx(TabShell,{title:s?`Settings \u2014 ${s.name}`:"Settings",focus:pane==="knobs",grow:1,children:!s?$jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:"No eikon open. Enter to create or pick one."})}):$jsxs($Fragment,{children:[$jsx("scrollbox",{id:"studio-knob-scroll",ref:ksb,scrollY:!0,flexGrow:1,contentOptions:COL,onMouseScroll:(e)=>e.stopPropagation(),children:rows3.map((row3,i)=>{let ni=navRows.findIndex((x2)=>x2.i===i),on=pane==="knobs"&&ni===sel,dim2=row3.kind==="knob"&&!src3;return $jsx(KnobRow,{id:`knob-${row3.kind}-${row3.id}`,row:row3,s,r,status,on,dim:dim2,peek:peek5,busy:row3.id==="fetch"&&fetching,onHover:()=>{if(ni>=0)setPane("knobs"),setSelBy(ni)},onClick:()=>{if(ni>=0)setSelBy(ni),setPane("knobs"),act(row3,"click")},onWheel:(d2)=>stepRow(row3,d2),onSlide:row3.knob?.kind!=="slider"?void 0:row3.kind==="tone"?(v2)=>setTone({contrast:+v2.toFixed(2)}):(v2)=>mutate((p)=>exports_eikon_knobs.edit(p,(k2)=>exports_eikon_knobs.setSlider(k2,row3.id,row3.knob,v2)))},`${row3.kind}:${r.name}:${row3.id}`)})}),$jsx("box",{flexShrink:0,height:HELP_H,marginTop:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:help})})]})}),strip=s?$jsx("box",{id:"studio-strip",flexShrink:0,height:18,children:$jsx(TabShell,{title:"States",focus:pane==="strip",children:$jsx(Strip,{s,frames:thumbs,stats,pending:pending3,focused:pane==="strip",onPick:(st)=>{setPane("strip"),mutate((p)=>exports_eikon_knobs.setState(p,st))},onEmpty:(st)=>doSource(st)})})}):null,top=wide?$jsxs("box",{flexDirection:"row",flexShrink:0,height:PREVIEW_H,children:[$jsx("box",{id:"studio-preview",flexShrink:0,width:PREVIEW_W,children:preview2}),$jsx("box",{id:"studio-knobs",flexGrow:1,flexBasis:0,minWidth:0,children:panel})]}):$jsxs($Fragment,{children:[$jsx("box",{id:"studio-preview",flexShrink:0,height:PREVIEW_H,children:preview2}),$jsx("box",{id:"studio-knobs",flexShrink:0,height:Math.max(rows3.length,1)+HELP_H+1+6,children:panel})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("scrollbox",{ref:outer,scrollY:!0,flexGrow:1,contentOptions:COL,children:[top,strip]}),$jsx(HintBar,{pairs:hint,suffix:saving?"\u25CF saving\u2026":s?.dirty?"\u25CF unsaved":void 0})]})});var import_react106=__toESM(require_react_production(),1);import{existsSync as existsSync21,readFileSync as readFileSync13}from"fs";import{basename as basename14,dirname as dirname13,join as join17}from"path";var EIKON_CARD=50,titleWidth=(title,rows3)=>Math.max(title.length,...rows3.map((r)=>r.name.length+4))+7,cardWidth=(lines3)=>Math.max(EIKON_CARD,...lines3.map((line4)=>line4.length+2)),EikonTitleList=(props)=>{let theme=useTheme().theme;return $jsx("box",{width:props.width,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:props.title,focus:props.focus,grow:1,children:$jsx("box",{flexDirection:"column",flexGrow:1,minHeight:0,children:$jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:"No eikons found."}):props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"row",height:1,paddingRight:3,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{width:2,children:$jsx("text",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,children:[r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})})]},r.key)})})})})})},EikonCardGrid=(props)=>{let theme=useTheme().theme;if(props.rows.length===0)return $jsx("box",{padding:1,children:props.empty??$jsx("text",{fg:theme.textMuted,children:"No eikons found."})});return $jsx("scrollbox",{ref:props.follow.ref,scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"row",flexWrap:"wrap",width:"100%",flexShrink:0,children:props.rows.map((r,i)=>{let on=i===props.sel;return $jsxs("box",{id:props.follow.id(i),flexDirection:"column",height:r.lines.length+2,width:cardWidth(r.lines),flexShrink:0,paddingX:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseMove:()=>props.onSel(i),onMouseDown:()=>{props.onSel(i),props.onUse(i)},children:[$jsx("box",{height:r.lines.length,overflow:"hidden",flexDirection:"column",children:r.lines.map((line4,j2)=>$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:line4||" "})},j2))}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:[on?"\u25B8 ":" ",r.active?"\u25CF ":" ",$jsx("strong",{children:r.name})]})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.author??"unknown"," \xB7 ",r.status]})})]},r.key)})})})};var PREVIEW2=54,EikonGallery=import_react106.memo((props)=>{let theme=useTheme().theme,dialog=useDialog(),toast=useToast(),keys=useKeys(),rev2=import_react106.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),rows3=import_react106.useMemo(()=>{let user=hermesPath("eikons"),own=exports_eikon.list(),map=new Map(own.map((x2)=>[x2.name.toLowerCase(),x2])),meta=own.map((x2)=>({inst:x2,ids:ids2(x2.manifest,x2.name,x2.sourceUrl)}));return listEikons([BUNDLED_EIKON_DIR,user]).map((e)=>{let slug3=e.path.startsWith(BUNDLED_EIKON_DIR)?e.meta.name.toLowerCase():basename14(dirname13(e.path)),man=manifest3(dirname13(e.path)),keys2=ids2(man,slug3),mine=meta.find((x2)=>x2.ids.some((k2)=>keys2.includes(k2)))?.inst??map.get(slug3);return{path:e.path,name:e.meta.name,slug:slug3,author:e.meta.author,bundled:e.path.startsWith(BUNDLED_EIKON_DIR),w:e.meta.width,h:e.meta.height,url:mine?.sourceUrl,hasSource:mine?.hasSource??!!exports_eikon.findSource(slug3),lifecycle:mine?.lifecycle,...man?{manifest:man}:{}}}).filter((r)=>!(r.bundled&&r.lifecycle))},[rev2]),active=usePref("eikon"),path7=import_react106.useMemo(()=>active?exports_eikon.baked(active):void 0,[active,rev2]),current2=(row3)=>path7===row3.path,[sel,setSel]=import_react106.useState(0),[pane,setPane]=import_react106.useState("list"),[act,setAct]=import_react106.useState(0),galleryFollow=useFollow("gal",(i)=>rows3[i]?.slug??i),gridFollow=useFollow("lib-grid",(i)=>rows3[i]?.slug??i);import_react106.useEffect(()=>{if(sel>=rows3.length)setSel(Math.max(0,rows3.length-1))},[rows3.length,sel]);let cur=rows3[sel],parsed=import_react106.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]),activate=(row3=cur)=>{if(!row3)return;if(row3.bundled)set("eikon",row3.slug);else exports_eikon.useInstalled(row3.slug);toast.show({variant:"success",message:`Avatar \u2192 ${row3.name}`})},doNew=import_react106.useCallback(async()=>{let res=await openNewEikon(dialog,{});if(!res)return;if(res.from==="blank")return exports_eikon.ensure(res.name),props.onEdit?.(res.name);if(res.from==="file"){exports_eikon.ensure(res.name);try{exports_eikon.adopt(res.name,res.file,"base")}catch(e){return toast.error(e instanceof Error?e:Error(String(e)))}return props.onEdit?.(res.name)}toast.show({variant:"info",message:`Installing '${res.name}' from ${res.src}\u2026`}),await exports_eikon.installPackage(res.src,{name:res.name}).then((out)=>{toast.show({variant:"success",message:`Installed '${out.name}' (${out.n} files)`})}).catch((e)=>toast.error(e instanceof Error?e:Error(String(e))))},[dialog,toast,props]),updateLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;try{let out=await exports_eikon.update(cur.slug);if("type"in out){if(!await openConfirm(dialog,{title:`Update active '${cur.name}'?`,danger:!0,body:`${out.message} The active avatar's backing package will change even though the selected name stays '${cur.slug}'.`,yes:"update active",no:"cancel"}))return;let done=await exports_eikon.update(cur.slug,{confirmActive:!0});if("type"in done)return toast.show({variant:"warning",message:done.message})}toast.show({variant:"success",message:`Updated ${cur.name}`})}catch(e){toast.error(e instanceof Error?e:Error(String(e)))}},[cur,dialog,toast]),submitLocal=import_react106.useCallback(async()=>{if(!cur||cur.bundled)return;let path8=submitPath(cur.slug);if(publishedInfo(path8)){toast.show({variant:"warning",title:"Published eikon",message:"Create a local draft before submitting",duration:6000});return}await openEikonSubmit(dialog,{name:cur.name,path:path8,submit:props.submit??submit2})},[cur,dialog,props.submit,toast]),del=async()=>{if(!cur||cur.bundled)return;let here=current2(cur),body=here?`Removes ${dirname13(cur.path)} and all its sources. This is the active avatar; deleting it will clear the active avatar selection.`:`Removes ${dirname13(cur.path)} and all its sources.`;if(!await openConfirm(dialog,{title:`Delete '${cur.name}'?`,danger:!0,body}))return;let removed=exports_eikon.remove(cur.slug,{confirmActive:here});if(removed)return toast.show({variant:"warning",message:removed.message});toast.show({variant:"info",message:`Deleted ${cur.name}`})},actions=import_react106.useMemo(()=>{if(!cur)return[];return[{key:"Enter",label:current2(cur)?"Use as active avatar (active)":"Use as active avatar",run:()=>activate()},...props.onEdit?[{key:"e",label:"Edit in Studio",run:()=>props.onEdit?.(cur.slug)}]:[],...!cur.bundled?[{key:"u",label:"Update local package",run:()=>void updateLocal()},{key:"s",label:"Share to catalog",run:()=>void submitLocal()},{key:"d",label:"Delete local eikon",run:()=>void del(),danger:!0}]:[]]},[cur,props.onEdit,updateLocal,submitLocal]);import_react106.useEffect(()=>{if(act>=actions.length)setAct(Math.max(0,actions.length-1))},[act,actions.length]);let cards=import_react106.useMemo(()=>rows3.map((r)=>{let p=(()=>{try{return parseEikonFile(r.path)}catch{return}})(),lines3=p?.resolve("state.idle")?.frames[0]??p?.states.get("idle")?.frames[0]??["(no preview)"];return{key:r.path,name:r.name,active:current2(r),author:r.author,status:current2(r)?"active":r.bundled?"bundled/system":"installed",lines:lines3}}),[rows3,path7]);useKeyboard((key3)=>{if(!props.focused||dialog.open())return;let plain=!key3.shift&&!key3.ctrl&&!key3.meta;if(key3.name==="tab")return setPane((p)=>p==="list"?"actions":"list");if(pane==="actions"){if(key3.name==="escape"||plain&&key3.name==="left"){setPane("list");return}if(plain&&key3.name==="up"){setAct((i)=>Math.max(0,i-1));return}if(plain&&key3.name==="down"){setAct((i)=>Math.min(actions.length-1,i+1));return}if(keys.match("list.activate",key3)||keys.match("list.toggle",key3)){actions[act]?.run();return}return}if(handleListKey(keys,key3,{count:rows3.length,setSel,page:galleryFollow.opts.page,scrollTo:(n)=>galleryFollow.ref.current?.scrollChildIntoView(galleryFollow.id(n)),onActivate:()=>activate(),onDelete:()=>void del(),onNew:doNew,onRefresh:()=>{exports_eikon.notifyRevision(),toast.show({variant:"info",message:"Reloaded",duration:1000})}}))return;if(key3.name==="u"&&cur&&!cur.bundled)return void updateLocal();if(key3.name==="s"&&cur&&!cur.bundled)return void submitLocal();if(key3.name==="e"&&cur&&props.onEdit)props.onEdit(cur.slug)});let listW=Math.max(13,...rows3.map((r)=>r.name.length+4))+7;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minHeight:0,children:[$jsx(EikonTitleList,{title:`Library (${rows3.length})`,rows:rows3.map((r)=>({key:r.path,name:r.name,active:current2(r)})),sel,focus:props.focused&&pane==="list",follow:galleryFollow,width:listW,onSel:setSel,onUse:(i)=>activate(rows3[i])}),$jsx(TabShell,{title:"Grid",grow:1,children:$jsx(EikonCardGrid,{rows:cards,sel,follow:gridFollow,onSel:setSel,onUse:(i)=>activate(rows3[i])})}),$jsx("box",{width:PREVIEW2,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:cur?`Preview \u2014 ${cur.name}`:"Preview",grow:1,children:$jsxs("box",{flexDirection:"column",flexGrow:1,padding:1,alignItems:"center",children:[$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur.path):$jsx("text",{fg:theme.textMuted,children:"No preview."})}),cur?$jsxs("box",{flexDirection:"column",width:48,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:cur.name})}),$jsxs("text",{fg:theme.textMuted,children:["Author: ",cur.author??"\u2014"]}),$jsxs("text",{fg:theme.textMuted,children:["Status: ",current2(cur)?"active":cur.bundled?"bundled/system":"installed"]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Source: ",gallerySource(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Trust: ",galleryTrust(cur)]}),$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:["Package: ",packageId(cur)]}),$jsx("text",{fg:theme.textMuted,children:sourceBadge(cur)}),$jsx("box",{height:1}),$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Actions"})}),actions.map((a,i)=>$jsx("box",{height:1,overflow:"hidden",paddingRight:1,backgroundColor:pane==="actions"&&i===act?theme.backgroundElement:void 0,onMouseDown:()=>{setPane("actions"),setAct(i),a.run()},children:$jsxs("text",{fg:a.danger?theme.error:theme.text,wrapMode:"none",children:[pane==="actions"&&i===act?"\u25B8 ":" ",a.label," [",a.key,"]"]})},a.label))]}):null]})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="list"?"actions":"library"],[keys.print("list.activate"),pane==="actions"?"run action":"use"],["\u2191\u2193",pane==="actions"?"action":"select"],[keys.print("list.new"),"new / install"],[keys.print("list.refresh"),"reload"],...cur&&props.onEdit?[["e","edit in Studio"]]:[]]})]})}),galleryTrust=(row3)=>{let t2=row3.lifecycle?.trust;if(t2==="verified")return"Verified";if(t2==="mismatch")return"Mismatch";if(t2==="unverified")return"Unverified";return row3.bundled?"Bundled":"Legacy local"},gallerySource=(row3)=>{let src3=row3.lifecycle?.source;if(src3)return src3.identity??src3.repo??src3.origin??src3.kind;if(row3.bundled)return"bundled/system";return"local"},packageId=(row3)=>typeof row3.manifest?.id==="string"?row3.manifest.id:row3.bundled?"bundled/system":"\u2014",manifest3=(dir2)=>{let file2=join17(dir2,"manifest.json");if(!existsSync21(file2))return;try{let raw2=JSON.parse(readFileSync13(file2,"utf8"));return raw2&&typeof raw2==="object"&&!Array.isArray(raw2)?raw2:void 0}catch{return}},sourceBadge=(row3)=>row3.hasSource?"\u25CF source":row3.url||row3.bundled?"\u25CB source available":"\u2014 no source",key3=(value)=>{try{let url2=new URL(value);if(url2.protocol==="http:"||url2.protocol==="https:"||url2.protocol==="file:")return url2.href.replace(/\/?$/,"/").toLowerCase()}catch{}return value.toLowerCase()},ids2=(man,name,url2)=>{let origin2=man?.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:void 0;return[...new Set([typeof man?.id==="string"?man.id:void 0,typeof origin2?.sourceKey==="string"?origin2.sourceKey:void 0,typeof origin2?.identityKey==="string"?origin2.identityKey:void 0,typeof origin2?.packageUrl==="string"?origin2.packageUrl:void 0,typeof origin2?.source==="string"?origin2.source:void 0,url2,name].filter((x2)=>!!x2).map(key3))]};var import_react109=__toESM(require_react_production(),1);var import_react108=__toESM(require_react_production(),1);var fmt3=(n)=>n==null?"size unknown":n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(1)} KiB`:`${(n/1024/1024).toFixed(1)} MiB`,choices=(row3,sizes)=>{if(row3.installState==="incompatible"||row3.installState==="mismatch")return[];if(!row3.installed)return[{label:"Eikon only",hint:fmt3(sizes?.eikon),value:"install"},{label:"Eikon + Source",hint:`${fmt3((sizes?.eikon??0)+(sizes?.source??0))} \xB7 Source files needed to edit Eikon in Studio`,value:"source"}];return[...!row3.active?[{label:"Use",hint:"set as active avatar",value:"use"}]:[],...row3.sourceDownloadable?[{label:"Download Source",hint:"needed to edit in Studio",value:"download"}]:[],...row3.removable?[{label:"Delete",value:"delete"}]:[]]},Action=(props)=>{let theme=useTheme().theme,opts=choices(props.row,props.sizes),[sel,setSel]=import_react108.useState(0),desc=opts.some((o)=>!!o.hint);return $jsxs("box",{flexDirection:"column",width:64,children:[$jsx("text",{fg:theme.text,children:$jsx("strong",{children:props.row.entry.name})}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.row.entry.description??"No description."}),$jsx("box",{height:1}),opts.length>0?$jsx("select",{focused:!0,width:62,height:Math.min(12,Math.max(1,opts.length*(desc?2:1))),options:opts.map((o)=>({name:o.label,description:o.hint??"",value:o.value})),selectedIndex:Math.min(sel,opts.length-1),showDescription:desc,showScrollIndicator:opts.length>6,backgroundColor:theme.backgroundPanel,focusedBackgroundColor:theme.backgroundPanel,textColor:theme.textMuted,focusedTextColor:theme.text,selectedBackgroundColor:theme.backgroundElement,selectedTextColor:theme.text,descriptionColor:theme.textMuted,selectedDescriptionColor:theme.textMuted,keyBindings:[{name:"home",action:"move-up-fast"},{name:"end",action:"move-down-fast"},{name:"space",action:"select-current"},{name:" ",action:"select-current"},{name:"return",action:"select-current"}],onChange:(i)=>setSel(i),onSelect:(i)=>{let opt=opts[i];if(opt)props.onPick(opt.value)}}):$jsx("text",{fg:theme.textMuted,children:props.row.reason??"No available actions."}),$jsx("box",{height:1}),$jsx("text",{fg:theme.textMuted,children:"[\u2191\u2193] move [Space/Enter] confirm [Esc] cancel"})]})};function openEikonMarketplaceAction(dialog,opts){return new Promise((resolve4)=>{let done=(v2)=>{resolve4(v2),dialog.clear()};dialog.replace($jsx(Action,{...opts,onPick:done}),()=>resolve4(null))})}init_perf();import{existsSync as existsSync22,readFileSync as readFileSync14,readdirSync as readdirSync7,writeFileSync as writeFileSync7}from"fs";import{createHash as createHash5}from"crypto";import{basename as basename15,dirname as dirname14,extname as extname4,join as join18}from"path";var DEFAULT_TIMEOUT=5000,DEFAULT_CACHE_LIMIT=24,dec=new TextDecoder;function hash2(data2){return`sha256:${createHash5("sha256").update(data2).digest("hex")}`}function keyIdentity(s){try{let u3=new URL(s);if(u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")return u3.href.replace(/\/?$/,"/")}catch{}return s}function manifestBaseKey(s){try{let u3=new URL(s);if((u3.protocol==="http:"||u3.protocol==="https:"||u3.protocol==="file:")&&u3.pathname.endsWith("/manifest.json"))return new URL(".",u3).href}catch{}return}function registryKey(man,source){if(man?.kind!=="eikon.package"||typeof man.id!=="string")return;let sourceKey=man.origin?.sourceKey??man.origin?.identityKey;if(sourceKey)return keyIdentity(sourceKey);try{let host=source?new URL(source).host:void 0;if(!host)return;return`registry:${host}:${man.id}${typeof man.version==="string"&&man.version?`@${man.version}`:""}`}catch{return}}function entryKeys(entry2){return[...new Set([entry2.identityKey,entry2.sourceKey].filter(Boolean).map(keyIdentity))]}function keysFor(inst){let keys=new Set,man=inst.manifest,origin2=typeof man?.origin?.source==="string"?man.origin.source:void 0,head=exports_eikon.header(inst.file),src3=typeof head?.source_url==="string"?head.source_url:inst.sourceUrl,registry2=registryKey(man,origin2);if(registry2)keys.add(registry2);if(origin2){keys.add(keyIdentity(origin2));let base2=manifestBaseKey(origin2);if(base2)keys.add(keyIdentity(base2))}if(src3){keys.add(keyIdentity(src3));let base2=manifestBaseKey(src3);if(base2)keys.add(keyIdentity(base2))}return[...keys]}function read(path7){try{let man=JSON.parse(readFileSync14(path7,"utf8"));return obj(man)?man:void 0}catch{return}}function chosen(active,name){return active===name||active==="default"&&name==="nous"}function media(dir2){return existsSync22(dir2)&&readdirSync7(dir2).length>0}function text3(value){return typeof value==="string"&&value?value:void 0}function life(name,man){let origin2=obj(man.origin)?man.origin:{},display2=obj(man.display)?man.display:{},src3=text3(origin2.source),identity2=text3(origin2.identityKey)??text3(origin2.sourceKey)??text3(origin2.packageUrl)??text3(origin2.repo)??src3,title=text3(display2.title)??text3(man.title),author=text3(display2.author)??text3(man.author);return{name,...title?{title}:{},...author?{author}:{},...text3(man.version)?{version:text3(man.version)}:{},source:{kind:text3(origin2.kind)??"default-catalog",...identity2?{identity:identity2}:{},...src3?{origin:src3}:{},...text3(origin2.repo)?{repo:text3(origin2.repo)}:{},...text3(origin2.selector)?{selector:text3(origin2.selector)}:{},...text3(origin2.catalogRoot)?{catalogRoot:text3(origin2.catalogRoot)}:{},...text3(origin2.sha)?{sha:text3(origin2.sha)}:{},...text3(origin2.packageUrl)?{packageUrl:text3(origin2.packageUrl)}:{}},trust:text3(origin2.trust)??"verified",active:chosen(get2("eikon"),name),removable:!1,updateable:Boolean(src3??text3(origin2.packageUrl)),updateAvailable:!1,dirty:!1,...text3(man.poster)?{poster:text3(man.poster)}:{},...obj(man.compatibility)?{compatibility:man.compatibility}:{},...text3(origin2.at)?{installedAt:text3(origin2.at)}:{}}}function bundled(xs){let names=new Set(xs.map((x2)=>x2.name.toLowerCase()));return listEikons([BUNDLED_EIKON_DIR]).flatMap((e)=>{let man=read(join18(dirname14(e.path),"manifest.json"));if(man?.kind!=="eikon.package")return[];let name=text3(man.name)??e.meta.name.toLowerCase();if(names.has(name.toLowerCase()))return[];let inst={name,file:e.path,source:exports_eikon.sourceDir(name),hasSource:media(exports_eikon.sourceDir(name)),sourceUrl:text3(man.origin?.source)??text3(man.origin?.packageUrl),manifest:man,lifecycle:life(name,man)};return[{...inst,manifest:man,identityKeys:keysFor(inst)}]})}function cacheKey(entry2){return[entry2.identityKey||entry2.sourceKey||entry2.id,entry2.runtimeUrl,entry2.trust?.runtimeDigest,entry2.trust?.runtimeSize].filter(Boolean).join("|")}function blob(url2){return/\/blobs\/sha256\/[^/?#]+/.test(url2)}function artifact(entry2){return entry2}function obj(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}function rawManifest(entry2){let raw2=entry2.raw;return obj(raw2.manifest)?raw2.manifest:void 0}function role(file2){if(file2.role==="source.base")return"base";if(file2.role?.startsWith("source."))return file2.role.slice(7);if(!file2.path)return;return basename15(file2.path,extname4(file2.path)).toLowerCase()||"base"}function sourceEntries2(man,strict=!1){if(!man)return[];try{let xs=entries(man).map(([r,rel2])=>[r,rel2]);if(xs.length)return xs;return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}catch(err){if(strict)throw err}return(man.files??[]).flatMap((file2)=>{if(typeof file2.path!=="string"||!file2.role?.startsWith("source"))return[];let r=role(file2);return r?[[r,file2.path]]:[]})}function sourceDescriptors2(man){return sourceEntries2(man).length>0}function sourceAvailable2(entry2,inst){return sourceDescriptors2(inst?.manifest)||sourceDescriptors2(rawManifest(entry2))}function trust(entry2){return entry2.trust}function boundTrust(entry2,raw2){let t2=trust(entry2),man=t2.manifestDigest,run=t2.runtimeDigest;if(!man&&!run)return"unverified";if(man&&hash2(raw2)!==man)throw Error(`catalog trust mismatch: manifest digest for ${entry2.name}`);let pkg=JSON.parse(dec.decode(raw2)),rel2=pkg.entrypoints?.default,got=rel2?pkg.files?.find((f)=>f.path===rel2)?.digest:void 0;if(run&&got!==run)throw Error(`catalog trust mismatch: runtime digest for ${entry2.name}`);return man&&run?"verified":"unverified"}function spec2(man,rel2){return man.files?.find((f)=>f.path===rel2)}async function sourceBytes(man,base2,rel2,opts){let file2=spec2(man,rel2);if(!file2?.digest||typeof file2.size!=="number")throw Error(`source descriptor missing digest or size: ${rel2}`);let raw2=await downloadBytes(new URL(rel2,base2).href,opts);if(raw2.length!==file2.size)throw Error(`source size mismatch: ${rel2}`);if(hash2(raw2)!==file2.digest)throw Error(`source digest mismatch: ${rel2}`);return raw2}function target(input){return typeof input==="string"?input:input instanceof URL?input.href:input.url}function verifiedCatalogTrust(entry2){let t2=trust(entry2);return typeof t2.manifestDigest==="string"&&t2.manifestDigest.length>0&&typeof t2.runtimeDigest==="string"&&t2.runtimeDigest.length>0}function installed(){let xs=exports_eikon.list().map((inst)=>({...inst,manifest:inst.manifest,identityKeys:keysFor(inst)}));return[...xs,...bundled(xs)]}function match2(entry2,xs){let keys=entryKeys(entry2),exact=xs.find((x2)=>x2.identityKeys.some((k2)=>keys.includes(k2)));if(exact)return{inst:exact,legacy:!1};let named=xs.find((x2)=>x2.name===entry2.name&&x2.identityKeys.length===0);if(named)return{inst:named,legacy:!0};return}function row3(entry2,xs){let usable=match2(entry2,xs),active=usable?chosen(get2("eikon"),usable.inst.name):!1,installed2=Boolean(usable),conflict=!usable&&chosen(get2("eikon"),entry2.name),blocked=entry2.compatibility?.available===!1,mismatch=usable?.inst.lifecycle.trust==="mismatch",installState=mismatch?"mismatch":blocked?"incompatible":active?"active":conflict?"active-name-conflict":!usable?"available":usable.legacy?"legacy-name-match":"installed",lifecycle2=usable?.inst.lifecycle??{name:entry2.name,title:entry2.title,author:entry2.author,version:entry2.version,source:{kind:"default-catalog",identity:entry2.sourceKey,packageUrl:entry2.packageUrl},trust:verifiedCatalogTrust(entry2)?"verified":"unverified",active:!1,removable:!1,updateable:!1,updateAvailable:!1,dirty:!1,...entry2.poster?{poster:entry2.poster}:{},compatibility:entry2.compatibility},available=sourceAvailable2(entry2,usable?.inst);return{entry:entry2,installed:installed2,active,installState,...usable?.inst.file?{installedPath:usable.inst.file,installedName:usable.inst.name}:{},...usable?.inst.manifest?{installedManifest:usable.inst.manifest}:{},lifecycle:lifecycle2,trust:lifecycle2.trust,updateable:lifecycle2.updateable,updateAvailable:lifecycle2.updateAvailable,removable:lifecycle2.removable,sourceIdentity:lifecycle2.source.identity,sourcePresent:usable?.inst.hasSource??!1,sourceAvailable:available,sourceDownloadable:Boolean(usable&&!usable.inst.hasSource&&available),reason:blocked?entry2.compatibility?.reason??"incompatible":mismatch?"trust mismatch":conflict?"install would replace the active avatar backing package":void 0,action:active?"active":installed2?"use":"install"}}function sizes(man){let files=Array.isArray(man.files)?man.files:[],eikon=files.filter((f)=>f.role==="runtime"||f.path===man.entrypoints?.default).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0),source=files.filter((f)=>typeof f.role==="string"&&f.role.startsWith("source")).map((f)=>f.size).filter((n)=>typeof n==="number").reduce((sum,n)=>sum+n,0);return{...eikon>0?{eikon}:{},...source>0?{source}:{}}}function abortErr(){return new DOMException("aborted","AbortError")}class MarketplaceService{catalog;fetcher;timeoutMs;previewCacheLimit;concurrency;allowPrivate;activeLoads=0;queue=[];cache=new Map;inFlight=new Map;constructor(catalog2,opts={}){this.catalog=catalog2,this.fetcher=opts.fetcher??fetch,this.timeoutMs=opts.timeoutMs??DEFAULT_TIMEOUT,this.previewCacheLimit=opts.previewCacheLimit??DEFAULT_CACHE_LIMIT,this.concurrency=Math.max(1,Math.floor(opts.concurrency??4)),this.allowPrivate=opts.allowPrivate===!0}rows(query=""){let entries2=searchCatalog(this.catalog.entries,query),xs=installed();return entries2.map((e)=>row3(e,xs))}entry(id){let key4=keyIdentity(id);return this.catalog.entries.find((e)=>keyIdentity(e.identityKey)===key4||keyIdentity(e.sourceKey)===key4||e.id===id||e.name===id)}dl(signal,fetcher=this.fetcher){return{allowPrivate:this.allowPrivate,fetcher:(input,init)=>fetcher(input,signal?{...init,signal}:init)}}runtime(entry2,signal){return async(input)=>{let url2=target(input),bound=keyIdentity(url2)===keyIdentity(entry2.runtimeUrl)&&(!!entry2.trust?.runtimeDigest||blob(url2)),raw2=await downloadBytes(url2,{...this.dl(signal),rejectContentEncoding:bound}),buf=raw2.buffer.slice(raw2.byteOffset,raw2.byteOffset+raw2.byteLength);return new Response(buf,{headers:{"content-length":String(raw2.length)}})}}cached(url2,raw2){let key4=keyIdentity(url2);return async(input,init)=>{if(keyIdentity(target(input))===key4)return new Response(raw2.slice(),{headers:{"content-length":String(raw2.length)}});return this.fetcher(input,init)}}async preview(id,opts={}){if(opts.signal?.aborted)throw abortErr();let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let key4=cacheKey(entry2),hit2=this.cache.get(key4);if(hit2!==void 0)return hit2;let active=this.inFlight.get(key4);if(active)return active;let p=this.enqueue(()=>this.loadPreview(entry2,opts)).finally(()=>this.inFlight.delete(key4));return this.inFlight.set(key4,p),p}async packageSizes(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);return sizes(JSON.parse(dec.decode(await downloadBytes(entry2.packageUrl,this.dl()))))}async install(id,opts={}){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);if(entry2.compatibility?.available===!1)throw Error(entry2.compatibility.reason??"eikon is incompatible");if(!match2(entry2,installed())&&chosen(get2("eikon"),entry2.name)&&!opts.confirmActive)throw Error(`Installing '${entry2.name}' will replace the active avatar's backing package. Pass confirmActive to install it.`);let raw2=await downloadBytes(entry2.packageUrl,this.dl()),state2=boundTrust(entry2,raw2),out=await exports_eikon.fetchSource(entry2.packageUrl,{name:entry2.name,media:opts.media===!0,downloader:this.dl(void 0,this.cached(entry2.packageUrl,raw2))}),ef=exports_eikon.file(out.name);if(!existsSync22(ef)){let art=await loadRuntimeArtifact(entry2,this.runtime(entry2),{allowPrivate:this.allowPrivate});await Bun.write(ef,art.bytes),exports_eikon.notifyRevision()}let mf=join18(exports_eikon.dir(out.name),"manifest.json"),man=JSON.parse(readFileSync14(mf,"utf8")),origin2=man.origin&&typeof man.origin==="object"&&!Array.isArray(man.origin)?man.origin:{};return writeFileSync7(mf,JSON.stringify({...man,origin:{...origin2,sourceKey:entry2.sourceKey,identityKey:entry2.identityKey,packageUrl:entry2.packageUrl,trust:state2}},null,2)+`
|
|
4164
|
+
`),out}async downloadSource(id){let entry2=this.entry(id);if(!entry2)throw Error(`marketplace: unknown eikon "${id}"`);let usable=match2(entry2,installed());if(!usable)throw Error(`marketplace: "${entry2.name}" is not installed`);if(!sourceAvailable2(entry2,usable.inst))throw Error(`marketplace: no source media published for "${entry2.name}"`);let raw2=await downloadBytes(entry2.packageUrl,this.dl());boundTrust(entry2,raw2);let man=JSON.parse(dec.decode(raw2)),xs=sourceEntries2(man,!0);if(xs.length===0)throw Error(`marketplace: no source media published for "${entry2.name}"`);let base2=new URL(".",entry2.packageUrl).href,dir2=exports_eikon.ensure(usable.inst.name).source,pairs=await Promise.all(xs.map(async([r,rel2])=>{let data2=await sourceBytes(man,base2,rel2,this.dl());return[r,exports_eikon.sourceName(man,r,rel2),data2]})),sources={};return await Promise.all(pairs.map(async([r,fname,data2])=>{await Bun.write(join18(dir2,fname),data2),sources[r]=fname})),exports_eikon.attachSources(usable.inst.name,sources),{name:usable.inst.name,n:pairs.length,bytes:pairs.reduce((sum,[,,data2])=>sum+data2.length,0)}}enqueue(run){return new Promise((resolve4,reject)=>{this.queue.push({run,resolve:resolve4,reject}),this.pump()})}pump(){if(this.activeLoads>=this.concurrency)return;let job=this.queue.shift();if(!job)return;this.activeLoads+=1,job.run().then(job.resolve,job.reject).finally(()=>{this.activeLoads-=1,this.pump()})}async loadPreview(entry2,opts){let ctl=new AbortController,timeout=setTimeout(()=>ctl.abort(),opts.timeoutMs??this.timeoutMs),off=()=>ctl.abort();opts.signal?.addEventListener("abort",off,{once:!0});try{let item=artifact(entry2),text4=(await loadRuntimeArtifact(item,this.runtime(item,ctl.signal),{signal:ctl.signal,allowPrivate:this.allowPrivate})).text;this.cache.set(cacheKey(entry2),text4);while(this.cache.size>this.previewCacheLimit)this.cache.delete(this.cache.keys().next().value);return text4}finally{clearTimeout(timeout),opts.signal?.removeEventListener("abort",off)}}}async function load4(opts={}){let query=opts.query??"";try{if(opts.catalog)publicCatalogUrl(opts.catalog,void 0,opts);let cat=await loadCatalog(opts.catalog,opts.fetcher??fetch,opts),service=new MarketplaceService(cat,opts),rows3=service.rows(query);return{status:rows3.length>0?"ready":"empty",query,rows:rows3,selected:rows3[0],service}}catch(err){return{status:"error",query,rows:[],error:err instanceof Error?err.message:String(err)}}}var NO_MARKET={status:"empty",query:"",rows:[]},DETAIL=54;function localCatalog(raw2){if(!raw2)return!1;try{let url2=new URL(raw2),host=url2.hostname.toLowerCase().replace(/^\[|\]$/g,"");return url2.protocol==="file:"||host==="localhost"||host==="127.0.0.1"||host==="0.0.0.0"||host==="::1"||host.endsWith(".localhost")}catch{return!1}}var filterRows=(rows3,query)=>{let q5=query.trim().toLowerCase();if(!q5)return rows3;return rows3.filter((r)=>[r.entry.name,r.entry.author,r.entry.description,r.entry.id].some((x2)=>typeof x2==="string"&&x2.toLowerCase().includes(q5)))},EikonMarketplace=import_react109.memo((props)=>{let toast=useToast(),dialog=useDialog(),keys=useKeys(),theme=useTheme().theme,rev2=import_react109.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision),[sel,setSel]=import_react109.useState(0),[searching,setSearching]=import_react109.useState(!1),[query,setQuery]=import_react109.useState(""),[state2,setState2]=import_react109.useState(NO_MARKET),[loading,setLoading]=import_react109.useState(!1),[installing,setInstalling]=import_react109.useState(!1),[previewState,setPreviewState]=import_react109.useState("idle"),[preview2,setPreview]=import_react109.useState(void 0),[pane,setPane]=import_react109.useState("grid"),previewSeq=import_react109.useRef(0),follow=useFollow("market",(i)=>state2.rows[i]?.entry.identityKey??i),listFollow=useFollow("market-list",(i)=>state2.rows[i]?.entry.identityKey??i),dims=useTerminalDimensions();import_react109.useEffect(()=>{if(sel>=state2.rows.length)setSel(Math.max(0,state2.rows.length-1))},[state2.rows.length,sel]);let selected=state2.rows[sel];import_react109.useEffect(()=>{if(!selected||!state2.service){setPreview(void 0);return}let id=++previewSeq.current,key4=selected.entry.identityKey;count("market:preview:load"),state2.service.preview(key4).then((text4)=>{if(previewSeq.current!==id)return;let e=parseEikon(text4),st=e.states.has(previewState)?previewState:"idle";setPreview({eikon:e,state:st,states:[...e.states.keys()]}),count("market:preview:ready")}).catch(()=>{if(previewSeq.current!==id)return;setPreview(void 0),count("market:preview:error")})},[selected,state2.service,previewState]),import_react109.useEffect(()=>()=>{previewSeq.current++,setPreview(void 0)},[]);let loadMarket=import_react109.useCallback((q5=query)=>{setLoading(!0);let end=mark("market:list:load"),catalog2=process.env.EIKON_URL;load4({catalog:catalog2,allowPrivate:localCatalog(catalog2),query:q5}).then((next2)=>{count("market:list:rows",next2.rows.length);let rows3=next2.service?filterRows(next2.service.rows(""),q5):filterRows(next2.rows,q5);setState2({...next2,status:rows3.length>0?"ready":"empty",rows:rows3,selected:rows3[0]}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))}).finally(()=>{end(),setLoading(!1)})},[query]),refreshMarket=import_react109.useCallback((svc,q5=query)=>{let rows3=filterRows(svc.rows(""),q5);setState2({status:rows3.length>0?"ready":"empty",query:q5,rows:rows3,selected:rows3[0],service:svc}),setSel((p)=>Math.max(0,Math.min(rows3.length-1,p)))},[query]);import_react109.useEffect(()=>{loadMarket(query)},[query,rev2,loadMarket]);let cycle3=import_react109.useCallback((by)=>{let states=preview2?.states,cur=preview2?.state;if(!states?.length||!cur)return;let at=Math.max(0,states.indexOf(cur));setPreviewState(states[(at+by+states.length)%states.length])},[preview2]),primary=import_react109.useCallback((idx)=>{let row4=state2.rows[idx??sel],svc=state2.service;if(!row4||!svc||installing)return;(async()=>{let sizes2=!row4.installed?await svc.packageSizes(row4.entry.identityKey).catch(()=>{return}):void 0,pick2=await openEikonMarketplaceAction(dialog,{row:row4,sizes:sizes2});if(!pick2)return;if(pick2==="use"){let name=row4.installedName??row4.entry.name;exports_eikon.useInstalled(name),toast.show({variant:"success",message:`Avatar \u2192 ${name}`}),refreshMarket(svc,query);return}if(pick2==="delete")return removeSelected(idx);setInstalling(!0);try{if(!(row4.installState==="active-name-conflict"?await openConfirm(dialog,{title:`Replace active '${row4.entry.name}'?`,danger:!0,body:`Installing this catalog package will replace the active avatar's backing package for '${row4.entry.name}' because another package with the same installed name is active.`,yes:"replace active",no:"cancel"}):!0))return;let out=pick2==="download"?await svc.downloadSource(row4.entry.identityKey):await svc.install(row4.entry.identityKey,{media:pick2==="source",confirmActive:row4.installState==="active-name-conflict"});toast.show({variant:"success",message:pick2==="download"?`Downloaded source for '${out.name}'`:`Installed '${out.name}' (${out.n} files)`}),refreshMarket(svc,query)}catch(err){toast.show({variant:"error",title:pick2==="download"?"Source download failed":"Install failed",message:err instanceof Error?err.message:String(err),duration:6000}),refreshMarket(svc,query)}finally{setInstalling(!1)}})()},[dialog,state2.rows,state2.service,sel,installing,toast,refreshMarket,query]),removeSelected=import_react109.useCallback(async(idx)=>{let row4=state2.rows[idx??sel],svc=state2.service,name=row4?.installedName??row4?.entry.name;if(!row4||!svc||!name||!row4.removable)return toast.show({variant:"warning",message:"This eikon is not removable"});let active=row4.active;if(!await openConfirm(dialog,{title:`Remove '${name}'?`,danger:!0,body:active?`Remove the local package for '${name}'. This is the active avatar; removal will clear the active avatar selection.`:`Remove the local package for '${name}'. This does not change the active avatar.`,yes:"remove",no:"cancel"}))return;let out=exports_eikon.remove(name,{confirmActive:active});if(out)return toast.show({variant:"warning",message:out.message});toast.show({variant:"info",message:`Removed '${name}'`}),refreshMarket(svc,query)},[dialog,query,refreshMarket,sel,state2.rows,state2.service,toast]);useKeyboard((key4)=>{if(!props.focused||dialog.open())return;if(searching){if(key4.name==="escape"||key4.name==="esc"){setSearching(!1);return}if(key4.name==="backspace"){setQuery((q5)=>q5.slice(0,-1)),setSel(0);return}let seq=typeof key4.sequence==="string"?key4.sequence:"",ch=key4.raw&&key4.raw.length===1?key4.raw:seq.length===1?seq:key4.name.length===1&&!key4.ctrl&&!key4.meta?key4.name:"";if(ch>=" "){setQuery((q5)=>q5+ch),setSel(0);return}return}let plain=!key4.shift&&!key4.ctrl&&!key4.meta;if(key4.name==="tab")return setPane((p)=>p==="grid"?"detail":"grid");if(pane==="detail"){if(key4.name==="escape"||plain&&key4.name==="left"){setPane("grid");return}if(plain&&key4.name==="right"){cycle3(1);return}if(keys.match("list.activate",key4)){primary();return}if(keys.match("list.toggle",key4)){cycle3(1);return}if(keys.match("list.search",key4)){setPane("grid"),setSearching(!0);return}if(keys.match("list.refresh",key4)){loadMarket(query);return}return}let move=(by)=>setSel((p)=>{let n=Math.max(0,Math.min(state2.rows.length-1,p+by));return follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n),n});if(plain&&key4.name==="left"){move(-1);return}if(plain&&key4.name==="right"){move(1);return}if(plain&&key4.name==="up"){move(-1);return}if(plain&&key4.name==="down"){move(1);return}if(handleListKey(keys,key4,{count:state2.rows.length,setSel,page:listFollow.opts.page,scrollTo:(n)=>{follow.opts.scrollTo?.(n),listFollow.opts.scrollTo?.(n)},onActivate:primary,onToggle:()=>cycle3(1),onSearch:()=>setSearching(!0),onRefresh:()=>loadMarket(query),onDelete:()=>void removeSelected()}))return}),count("market:render");let titles=state2.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active})),cards=state2.rows.map((r)=>({key:r.entry.identityKey,name:r.entry.name,active:r.active,author:r.entry.author,status:stateLabel(r,!0),lines:posterLines(r.entry.poster)})),listW=titleWidth(`Catalog (${state2.rows.length})`,titles),showGrid=dims.width>=190;return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsxs("box",{flexDirection:"row",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(EikonTitleList,{title:`Catalog (${state2.rows.length})${searching?` Search: ${query}`:""}`,rows:titles,sel,focus:props.focused&&pane==="grid",follow:listFollow,width:listW,onSel:setSel,onUse:primary}),showGrid?$jsx(TabShell,{title:"Posters",grow:1,children:state2.error?$jsx("box",{padding:1,children:$jsxs("text",{fg:theme.error,wrapMode:"word",children:["Catalog unavailable: ",state2.error]})}):loading&&state2.rows.length===0?$jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:"Loading shared eikons\u2026"})}):$jsx(EikonCardGrid,{rows:cards,sel,follow,empty:$jsx("text",{fg:theme.textMuted,children:"No catalog eikons match. Press / to change search."}),onSel:setSel,onUse:primary})}):null,$jsx("box",{width:DETAIL,flexShrink:0,minHeight:0,children:$jsx(TabShell,{title:selected?`Details \u2014 ${selected.entry.name}`:"Details",focus:props.focused&&pane==="detail",grow:1,children:$jsx(MarketplaceDetail,{row:selected,loading,installing,onUse:()=>primary(),onFocus:()=>setPane("detail"),onState:setPreviewState,preview:preview2})})})]}),$jsx(HintBar,{pairs:[["Tab",pane==="grid"?"details":"catalog"],[keys.print("list.activate"),"actions"],[pane==="detail"?"\u2192/Space":"\u2191\u2193\u2190\u2192/Pg",pane==="detail"?"state":"select"],[keys.print("list.search"),searching?"typing search":"search"],[keys.print("list.refresh"),"reload"],["d","delete in modal"],["Space","preview"]]})]})}),posterLines=(poster2)=>{let lines3=poster2?poster2.split(`
|
|
4165
|
+
`):[];return lines3.length?lines3:["(no poster)"]},MarketplaceDetail=(props)=>{let theme=useTheme().theme,r=props.row;if(!r)return $jsx("box",{padding:1,children:$jsx("text",{fg:theme.textMuted,children:props.loading?"Loading shared eikons\u2026":"No catalog entry selected."})});let previewState=props.preview?.state??"idle",states=props.preview?.states??[previewState];return $jsxs("box",{flexDirection:"column",padding:1,onMouseDown:props.onFocus,children:[props.preview?$jsx("box",{alignItems:"center",justifyContent:"center",width:48,height:24,flexShrink:0,overflow:"hidden",children:$jsx(AnimatedAvatar,{state:props.preview.state,eikon:props.preview.eikon},`${r.entry.identityKey}:${props.preview.state}`)}):null,$jsx("box",{height:1,overflow:"hidden",children:$jsx("text",{fg:r.active?theme.accent:theme.text,wrapMode:"none",children:$jsxs("strong",{children:[r.active?"\u25CF ":"",r.entry.name]})})}),$jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["by ",r.entry.author??"unknown"]})}),$jsx("box",{minHeight:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:r.entry.description??"No description."})}),$jsx("box",{flexDirection:"row",flexWrap:"wrap",flexShrink:0,children:states.map((s,i)=>$jsx(FilterChip,{label:s,state:s===previewState?"in":"off",gap:i===0?0:1,color:theme.primary,textColor:theme.textMuted,onMouseDown:()=>props.onState(s)},s))}),$jsx(DetailRow2,{label:"Status",value:stateLabel(r),block:!0}),$jsx(DetailRow2,{label:"Trust",value:trustLabel(r),block:!0}),$jsx(DetailRow2,{label:"Source",value:sourceText(r),block:!0}),$jsx(DetailRow2,{label:"Compat",value:compatText(r)}),$jsx(DetailRow2,{label:"Digest",value:digest2(r)??"unknown",block:!0})]})},DetailRow2=(props)=>{let theme=useTheme().theme;if(props.block)return $jsx("box",{flexDirection:"column",minHeight:props.label==="Status"?2:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:[props.label,": ",props.value]})});return $jsx("box",{height:1,overflow:"hidden",children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[props.label,": ",props.value]})})},shortDigest=(value)=>{if(!value)return;let[algo,hash3]=value.includes(":")?value.split(":",2):[void 0,value];if(!hash3||hash3.length<=16)return value;return algo?`${algo}:${hash3.slice(0,12)}\u2026`:`${hash3.slice(0,12)}\u2026`},digest2=(row4)=>{let t2=row4.entry.trust;return shortDigest(t2.manifestDigest??t2.runtimeDigest??t2.digest)},trustLabel=(row4)=>{let t2=row4.trust==="mismatch"?"Mismatch":row4.trust==="verified"?"Verified":row4.trust==="unverified"?"Unverified":"Trust unknown";return row4.reason&&row4.trust==="mismatch"?`${t2}: ${row4.reason}`:t2},sourceText=(row4)=>row4.sourceIdentity??row4.lifecycle.source.packageUrl??row4.entry.sourceKey??row4.entry.packageUrl,compatText=(row4)=>row4.installState==="incompatible"?`Blocked: ${row4.reason??"requires newer Herm/eikon"}`:row4.installState==="active-name-conflict"?`Requires confirmation: ${row4.reason}`:"Compatible",stateLabel=(row4,short2=!1)=>{let base2=row4.installState==="active-name-conflict"?"active name conflict":row4.active?"active":row4.installed?"installed":"not installed";if(short2)return base2;let src3=row4.sourcePresent?" \xB7 source present":row4.sourceDownloadable?" \xB7 source downloadable":row4.sourceAvailable?" \xB7 source available":"",rm=row4.removable?" \xB7 removable":row4.installed?" \xB7 not removable":"";return`${base2}${src3}${rm}`};var EikonGroup=import_react111.memo((props)=>{let labels=SUB_TABS[EIKON_TAB],[target2,setTarget]=import_react111.useState(void 0);import_react111.useEffect(()=>{if(props.sub>=labels.length)props.setSub(0)},[props.sub,labels.length]);let edit2=import_react111.useCallback((name)=>{setTarget(name),props.setSub(2)},[props]),hint="shift+\u2190/\u2192 sub";return $jsxs("box",{flexDirection:"column",flexGrow:1,minWidth:0,minHeight:0,children:[$jsx(SubTabBar,{tabs:labels,active:props.sub,onChange:props.setSub,hint}),$jsxs("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:[$jsx(Pane4,{visible:props.sub===0,children:$jsx(EikonGallery,{focused:!!props.focused&&props.sub===0,onEdit:edit2})}),$jsx(Pane4,{visible:props.sub===1,children:$jsx(EikonMarketplace,{focused:!!props.focused&&props.sub===1})}),$jsx(Pane4,{visible:props.sub===2,children:$jsx(EikonStudio,{focused:!!props.focused&&props.sub===2,name:target2})})]})]})}),Pane4=({visible:visible2,children:children2})=>visible2?$jsx("box",{flexGrow:1,minWidth:0,minHeight:0,flexDirection:"column",children:children2}):null;var import_react112=__toESM(require_react_production(),1);var FRAME={cw:16,ch:8,tw:20,tv:8},TL=["\u2800\u2880\u28E4\u2824\u2884\u28C0\u2804\u2880\u28E0\u28E4\u28C4\u2864\u2844\u2840\u2800\u2800","\u2800\u28DC\u2841\u28A9\u28C8\u2842\u2880\u28CB\u28ED\u2809\u2808\u2888\u28EE\u28FB\u2851\u28F6","\u2800\u28B8\u2856\u28BF\u280F\u28E4\u28F6\u28FD\u28EB\u28B6\u28E2\u284C\u2839\u28E7\u284F\u283B","\u2800\u2808\u2864\u2892\u28E6\u28BB\u28FF\u28FF\u28FF\u28BF\u28C5\u2847\u28C6\u2849\u2802\u2880","\u2801\u28B8\u284F\u2818\u280B\u289E\u28B3\u28FF\u28FF\u28DF\u284D\u284D\u28E4\u2805\u2800\u28A8","\u2800\u2824\u28AF\u28C6\u28C0\u2819\u28A6\u28FF\u284B\u2880\u28DC\u2807\u28C1\u28D2\u28CA\u28C9","\u2800\u2880\u28F7\u28DD\u28FB\u28F6\u28F6\u2884\u280D\u2818\u2841\u2847\u28E7\u28E0\u28E4\u2862","\u2800\u2800\u2818\u288E\u28BF\u28EF\u2803\u2801\u2864\u28DA\u287C\u2800\u284F\u28F9\u28FF\u2869"],TR=["\u2800\u2800\u2880\u28A0\u28A0\u28E0\u28E4\u28C0\u2840\u2820\u28C0\u2860\u2824\u28E4\u28C0\u2800","\u28F6\u288A\u28DF\u28F5\u2841\u2801\u2809\u28ED\u28D9\u2800\u2890\u28C2\u284D\u2888\u28E3\u2800","\u281F\u28B9\u28FC\u280F\u28A1\u28D4\u28B6\u28DD\u28EF\u28F6\u28E4\u2839\u287F\u28B2\u2847\u2800","\u2840\u2801\u2889\u28F0\u28B8\u28E8\u287F\u28FF\u28FF\u28FF\u285F\u28F4\u2852\u28A4\u2801\u2800","\u2845\u2804\u2828\u28E4\u28A9\u28A9\u28FB\u28FF\u28FF\u285E\u2873\u2819\u2803\u28B9\u2847\u2800","\u28C9\u28D1\u28D2\u28C8\u2838\u28E3\u2840\u2899\u28FF\u2874\u280B\u28C0\u28F0\u287D\u2824\u2880","\u2884\u28E4\u28C4\u28F8\u28B8\u2888\u2803\u2829\u2860\u28F6\u28F6\u28DF\u28EB\u28FE\u2802\u2800","\u288D\u28FF\u289F\u28B9\u2800\u28A7\u28D2\u28A4\u2801\u2808\u28FD\u287F\u2871\u2807\u2800\u2800"],BL=["\u2800\u2800\u28C0\u28FF\u28FF\u285F\u2801\u2800\u283B\u28AC\u28F3\u2800\u28C7\u28F2\u28DF\u28BF","\u2800\u2890\u287A\u28DB\u286F\u28ED\u2837\u280C\u2882\u2880\u2842\u2847\u284F\u2819\u281B\u2827","\u2800\u2816\u287C\u2809\u2809\u28A0\u28F0\u2825\u28AD\u2818\u28DB\u28C4\u288B\u28C9\u28C9\u2859","\u2800\u28B8\u284C\u2880\u28E0\u28F5\u28FF\u28FF\u28FF\u28FF\u28E8\u2803\u2837\u2802\u2810\u288D","\u2800\u2800\u283B\u281D\u283F\u28F4\u28FF\u28FF\u287F\u28FF\u28DF\u28CB\u284F\u2841\u2804\u2818","\u2800\u28B8\u28F0\u28F6\u28C4\u283B\u283F\u28FF\u28F9\u2830\u281F\u2882\u28A0\u285F\u28C6\u28F4","\u2800\u28AA\u2849\u2838\u28FB\u2807\u2800\u285D\u28DB\u2880\u2840\u28D8\u285F\u2877\u28EB\u286F","\u2800\u2819\u283B\u282A\u281C\u2813\u2802\u2808\u281B\u2813\u281B\u2819\u281A\u2808\u2801\u2800"],BR2=["\u287F\u28FB\u28D6\u28F8\u2800\u28DE\u2861\u281F\u2880\u2804\u28BB\u28FF\u28FF\u28C0\u2800\u2800","\u2836\u281B\u280B\u28B9\u28B8\u2890\u2840\u2850\u2821\u283E\u28ED\u28BD\u28DB\u2897\u2842\u2800","\u288B\u28C9\u28C9\u2859\u28E0\u28DB\u2803\u286D\u282C\u28C6\u2844\u2809\u2829\u28A7\u2832\u2800","\u2869\u2802\u2810\u283E\u2818\u28C5\u28FF\u28FF\u28FF\u28FF\u28EE\u28C4\u2840\u28B1\u2847\u2800","\u2803\u2880\u2888\u28B3\u28D9\u28FB\u28FF\u28DF\u28FF\u28FF\u28E6\u283F\u282B\u281F\u2800\u2800","\u28E6\u28F0\u28BB\u2844\u2850\u283B\u2803\u28CF\u28FF\u283F\u281F\u28E0\u28F6\u28C6\u2847\u2800","\u28BD\u28DD\u28AF\u28BB\u28C3\u2880\u2840\u28DB\u28E9\u2800\u2838\u28DF\u2807\u2889\u2855\u2800","\u2801\u2800\u2801\u2813\u280B\u281B\u281A\u281B\u2801\u2810\u281A\u2823\u2807\u281F\u280B\u2800"],T2=["\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800","\u2844\u28E2\u28F4\u28F6\u2836\u2816\u2832\u28CC\u2818\u2809\u2822\u285B\u28A1\u2834\u2832\u2836\u28F0\u2896\u28B4\u28E4","\u28FE\u28E5\u283F\u2800\u28E0\u28B0\u283F\u28BE\u2850\u283E\u283F\u2887\u2873\u28FF\u28D7\u2804\u2800\u2823\u28D1\u28F5","\u28BE\u285F\u2804\u2810\u28AD\u28CD\u2896\u2844\u2828\u28BB\u28EB\u283D\u287C\u287F\u28BD\u28A5\u2842\u2804\u283B\u287D","\u2813\u287B\u28B6\u28C4\u2848\u2818\u282D\u281A\u280D\u28BB\u2849\u280B\u280B\u282D\u2803\u2803\u2861\u28F6\u28DF\u28BE","\u2801\u2804\u2809\u2809\u281A\u2824\u2824\u282C\u281F\u2830\u2827\u280A\u282F\u2834\u2824\u2813\u281B\u2809\u2810\u2822","\u28DB\u28DB\u285F\u28DB\u285B\u28DB\u28DB\u289B\u28DB\u28DB\u285B\u28DB\u28DB\u289B\u28FB\u28FB\u28DF\u281B\u28FB\u28BB","\u28CA\u28C9\u28C9\u28DB\u28CB\u28D9\u28CB\u28FC\u28F7\u28E5\u28EF\u28FA\u28CB\u28F5\u28F7\u28ED\u28D9\u28D1\u28FB\u28FD"],B2=["\u28FF\u28BF\u28FF\u28FF\u28BF\u28FF\u287F\u287F\u28FF\u28FF\u283F\u28FF\u28BF\u287F\u28FF\u28FF\u287F\u28FF\u287F\u28BF","\u28C3\u28DB\u28C8\u28D3\u28DA\u28DA\u28C3\u28D9\u28DB\u28C9\u28DB\u28DB\u28C1\u28DB\u28D9\u28D9\u28CB\u28D8\u28C9\u28D9","\u2820\u2884\u2884\u28C0\u2864\u28E4\u2810\u28E0\u2884\u28A0\u2844\u2864\u28C4\u2800\u2864\u2884\u28C0\u2840\u2880\u2880","\u28F1\u282C\u282B\u2811\u2881\u28E0\u28A0\u286B\u28E1\u28E0\u28E4\u28C9\u2885\u2884\u28C4\u2809\u283B\u2850\u28A5\u28CC","\u2894\u28C8\u2800\u28B0\u2841\u28B6\u28FF\u28FF\u28DF\u28FF\u28C3\u285B\u2815\u280D\u28E6\u28C3\u2844\u2802\u28F9\u2862","\u287F\u288F\u2884\u2800\u2803\u28EB\u28FF\u289C\u28A9\u28F6\u28E6\u2809\u2876\u28FE\u2856\u281B\u2800\u28E0\u285B\u287F","\u283C\u28BE\u283F\u28F5\u28D6\u28D8\u2834\u2803\u2808\u2886\u2880\u2800\u2873\u2824\u28C2\u28F2\u28FE\u282F\u281A\u280F","\u2800\u2800\u2801\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u280B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800"],L2=["\u2800\u2800\u2890\u289F\u28FE\u283F\u282E\u2836\u2877\u28EA\u283E\u2802\u2857\u28AD\u28BF\u28B9","\u2800\u2800\u28E8\u2855\u2809\u2861\u2824\u28C1\u284C\u282A\u28A7\u2801\u2847\u28F0\u28FF\u28BC","\u2800\u2800\u2839\u2843\u28BE\u28D5\u28F7\u2866\u28D3\u2840\u2849\u2846\u284F\u28F6\u2863\u28FB","\u2800\u28B0\u2876\u28AC\u28ED\u285C\u28FF\u28FF\u28EF\u2888\u2893\u2801\u284F\u28DA\u287E\u28FF","\u2800\u2818\u285B\u288A\u28D9\u2823\u2887\u28AF\u28FF\u2828\u286D\u2841\u2867\u28BC\u28F2\u28FF","\u2800\u2800\u28B1\u2849\u28BF\u2847\u2824\u28DD\u2844\u2800\u2841\u2801\u284F\u28F6\u2896\u28BF","\u2800\u2800\u28B0\u28E7\u2840\u2813\u2813\u2809\u2881\u28F4\u284D\u2800\u2847\u283A\u283D\u28BA","\u2800\u2800\u2828\u283A\u28FD\u28F7\u28E6\u2874\u285A\u2803\u2880\u2800\u2847\u287E\u28FF\u28B9"],R=["\u284F\u287F\u286D\u28BA\u2880\u2837\u289D\u28BE\u2836\u2835\u283F\u28F7\u287B\u2842\u2800\u2800","\u2867\u28FF\u28C6\u28B8\u2800\u287C\u2815\u28A1\u28C0\u2824\u288C\u2809\u28AA\u28C5\u2801\u2800","\u28DF\u289C\u28F6\u28B9\u28B0\u2889\u2880\u28DA\u28B4\u28FE\u28EA\u2877\u2898\u280F\u2800\u2800","\u28FF\u28B7\u285B\u28B9\u2808\u285A\u2841\u28FD\u28FF\u28FF\u28A3\u28ED\u2865\u28B6\u2846\u2800","\u28FF\u28D6\u2867\u28BC\u2888\u28AD\u2805\u28FF\u287D\u2878\u2858\u28CB\u2851\u289B\u2803\u2800","\u287F\u2872\u28F6\u28B9\u2808\u2888\u2800\u28A0\u28EB\u2824\u28B8\u287F\u2889\u2846\u2800\u2800","\u2857\u282F\u2817\u28B8\u2800\u28A9\u28E6\u2848\u2809\u281A\u281A\u2880\u28FC\u2846\u2800\u2800","\u284F\u28FF\u28AF\u28B8\u2800\u2880\u2818\u2893\u28A6\u28B6\u28FE\u28EF\u2817\u2805\u2800\u2800"];function frame(w2,h2){let{cw,ch,tw,tv}=FRAME,mw=w2-2*cw,mh=h2-2*ch,inner={x:cw,y:ch,w:Math.max(0,mw),h:Math.max(0,mh)};if(mw<4||mh<2)return{lines:[],inner};let repH=(p,span2)=>p.map((l2)=>l2.repeat(Math.ceil(span2/tw)).slice(0,span2)),repV=(p,span2)=>Array.from({length:span2},(_2,i)=>p[i%tv]),t2=repH(T2,mw),b2=repH(B2,mw),l=repV(L2,mh),r=repV(R,mh),mid2=" ".repeat(mw),out=[];for(let i=0;i<ch;i++)out.push(TL[i]+t2[i]+TR[i]);for(let i=0;i<mh;i++)out.push(l[i]+mid2+r[i]);for(let i=0;i<ch;i++)out.push(BL[i]+b2[i]+BR2[i]);return{lines:out,inner}}import{readFileSync as readFileSync15}from"fs";import{join as join19}from"path";var FALLBACK=["`@file:path/to/file.py` injects file contents directly into your message.","`/title <name>` names the session \u2014 resume it later from the Sessions tab.","Ctrl+G opens $EDITOR seeded with the composer contents.","Ctrl+Z suspends to the shell; `fg` resumes.","Pasting 5+ lines collapses to a `[Pasted #N \u2026]` placeholder.","Click a user message in the transcript to rewind to that point."],HL=/(\/[a-z][\w-]*|@[\w:./-]+|(?:Ctrl|Alt|Shift)\+\S+|`[^`]+`|"[^"]+")/g;function splitTip(tip2){let out=[],i=0;for(let m2 of tip2.matchAll(HL)){let j2=m2.index;if(j2>i)out.push({t:tip2.slice(i,j2),hl:!1});out.push({t:m2[0].replace(/^`|`$/g,""),hl:!0}),i=j2+m2[0].length}if(i<tip2.length)out.push({t:tip2.slice(i),hl:!1});return out}var cache5=null;function loadTips(){if(cache5)return cache5;try{let body=readFileSync15(join19(hermesAgentRoot(),"hermes_cli","tips.py"),"utf8").split(/^TIPS\s*=\s*\[/m)[1]?.split(/^\]/m)[0]??"",tips=[];for(let line4 of body.split(`
|
|
4166
|
+
`)){let m2=line4.match(/^\s+"((?:[^"\\]|\\.)*)",?\s*$/);if(m2)tips.push(m2[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"))}cache5=tips.length>10?tips:FALLBACK}catch{cache5=FALLBACK}return cache5}function randomTip(prev){let t2=loadTips();if(t2.length<2)return t2[0]??"";let pick2=t2[Math.floor(Math.random()*t2.length)];while(pick2===prev)pick2=t2[Math.floor(Math.random()*t2.length)];return pick2}import{readFileSync as readFileSync16,existsSync as existsSync23}from"fs";import{dirname as dirname15,join as join20}from"path";var pkgVersion=(d2,up=4)=>{let p=join20(d2,"package.json");if(existsSync23(p))return JSON.parse(readFileSync16(p,"utf8")).version;return up>0?pkgVersion(dirname15(d2),up-1):"0.0.0"},VERSION=pkgVersion(import.meta.dirname);function parseLaunch(argv){let splash=!0;for(let i=0;i<argv.length;i++){let a=argv[i];if(a==="--no-splash"){splash=!1;continue}if(a==="-c"||a==="--continue")return{mode:"resume",splash};if(a==="--resume"){let next2=argv[i+1];return next2&&!next2.startsWith("-")?{mode:"resume",sid:next2,splash}:{mode:"resume",splash}}}return{mode:"new",splash}}var HELP2=`herm \u2014 OpenTUI client for hermes-agent
|
|
4165
4167
|
|
|
4166
4168
|
Usage:
|
|
4167
4169
|
herm start a fresh session
|
|
@@ -4170,24 +4172,24 @@ Usage:
|
|
|
4170
4172
|
herm --no-splash skip the launch splash
|
|
4171
4173
|
herm -v, --version print version
|
|
4172
4174
|
herm -h, --help show this help
|
|
4173
|
-
`;var TIERS=["block","slick","tiny"],pickFont=(innerW)=>TIERS.find((f)=>measureText({text:"HERM",font:f}).width<=innerW)??"tiny",clip=(s,w2)=>[...s].length<=w2?s:[...s].slice(0,Math.max(1,w2-1)).join("")+"\u2026";function Splash(p){let theme=useTheme().theme,ref=import_react112.useRef(null),[box2,setBox]=import_react112.useState({w:0,h:0}),renderer=useRenderer();import_react112.useEffect(()=>{let cb=async()=>{let r=ref.current;if(!r)return;setBox((b2)=>b2.w===r.width&&b2.h===r.height?b2:{w:r.width,h:r.height})};return renderer.setFrameCallback(cb),()=>renderer.removeFrameCallback(cb)},[renderer]);let{lines:lines3,inner}=import_react112.useMemo(()=>frame(box2.w,box2.h),[box2.w,box2.h]),font=import_react112.useMemo(()=>pickFont(inner.w),[inner.w]),[tip2,setTip]=import_react112.useState(()=>randomTip()),behind=p.info?.behind,sub2=[`v${VERSION}`,p.info?`hermes ${p.info.agentVersion??"?"}`:"\u2026",behind==null?null:behind===0?"up to date":`${behind} behind`,p.info?.model].filter(Boolean).join(" \xB7 "),prompt=p.last&&!p.composing,title=p.last?.title?.trim()||p.last?.id;return $jsxs("box",{ref,position:"absolute",left:0,top:0,right:0,bottom:0,zIndex:50,backgroundColor:theme.background,children:[lines3.map((l,i)=>$jsx("box",{position:"absolute",top:i,left:0,height:1,children:$jsx("text",{fg:theme.accent,children:l})},i)),lines3.length>0&&$jsxs("box",{position:"absolute",left:inner.x,top:inner.y,width:inner.w,height:inner.h,flexDirection:"column",alignItems:"center",justifyContent:"center",children:[$jsx("box",{children:$jsx("ascii-font",{text:"HERM",font,color:[theme.accent,theme.textMuted],selectable:!1})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:clip(sub2,inner.w)})}),p.news?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:clip(`\u203A ${p.news}`,inner.w)})}):null,$jsx("box",{height:2}),p.loading?$jsx("text",{fg:theme.textMuted,children:$jsx("span",{fg:theme.accent,children:"Loading\u2026"})}):prompt?$jsxs($Fragment,{children:[$jsxs("text",{fg:theme.textMuted,children:["continue ",$jsxs("span",{fg:theme.text,children:['"',clip(title??"",Math.max(8,inner.w-14)),'"']})," ?"]}),$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{fg:theme.accent,children:"[enter]"})," yes \xB7 type to start fresh"]})]}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{fg:theme.accent,children:"[enter]"})," to send"]}),inner.h>=14?$jsx("box",{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",alignItems:"center",onMouseDown:()=>setTip((t2)=>randomTip(t2)),children:$jsx("text",{wrapMode:"word",children:splitTip(clip(tip2,inner.w*2)).map((s,i)=>$jsx("span",{fg:s.hl?theme.accent:theme.textMuted,children:s.t},i))})}):null]})]})}init_sessions_db();function openMessage(dialog,m2,ops){let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");dialog.replace($jsx(DialogSelect,{title:"Message Actions",options:[{title:"Copy",value:"copy",description:"message text to clipboard"},{title:"Rewind here",value:"rewind",description:"undo back to this turn (destructive)"},{title:"Fork here",value:"fork",description:"branch a new session at this point"}],onSelect:(o)=>{if(dialog.clear(),o.value==="copy")return void copy(text4);if(o.value==="rewind")return ops.rewind(m2);if(o.value==="fork")return ops.fork(m2)}}))}var LOCAL_NAMES=new Set(["clear","new","theme","help","keys","logs","title","rollback","save","history","status","usage","profile","steer","reload","reload-mcp","reload-skills","chafa","splash","skin","resume","branch","compress","undo","redo","retry","model","yolo","quit","copy","paste","image","background","voice","mouse","redraw","queue","stash","compact","setup","browser"]),LOCAL_COMMANDS=[{name:"clear",description:"Clear chat messages",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"new",description:"Start a new session",category:"Client",aliases:["reset"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"theme",description:"Switch color theme or mode",category:"Client",aliases:[],argsHint:"[light|dark]",subcommands:[],source:"local",target:"local"},{name:"help",description:"Show keyboard shortcuts",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"keys",description:"Rebind keyboard shortcuts",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"logs",description:"Show gateway stderr log",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"title",description:"Set session title",category:"Client",aliases:[],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"rollback",description:"Browse & restore checkpoints",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"history",description:"Server-side transcript viewer",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"status",description:"Version, model, paths",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"usage",description:"Credits, account status, tokens, context fill, cost",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"profile",description:"Active profile details",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"steer",description:"Inject a note mid-turn (no interrupt)",category:"Session",aliases:[],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"reload-mcp",description:"Restart MCP servers & rediscover tools",category:"Session",aliases:[],argsHint:"[now|always]",subcommands:["now","always"],source:"local",target:"local"},{name:"reload",description:"Hot-reload ~/.hermes/.env (API keys)",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"reload-skills",description:"Re-scan ~/.hermes/skills/ for added/removed skills",category:"Session",aliases:["reload_skills"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"chafa",description:"Render image via chafa (demo)",category:"Client",aliases:[],argsHint:"<path>",subcommands:[],source:"local",target:"local"},{name:"splash",description:"Show the launch splash",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"goal",description:"Set/control the session goal",category:"Session",aliases:[],argsHint:"[text|done|pause|resume|clear|status]",subcommands:["done","pause","resume","clear","status"],source:"command",target:"gateway"},{name:"skin",description:"Switch Hermes skin (+ theme + eikon)",category:"Client",aliases:[],argsHint:"[name]",subcommands:[...SKINS],source:"local",target:"local"},{name:"voice",description:"Toggle voice recording",category:"Client",aliases:[],argsHint:"[on|off|status|tts]",subcommands:["on","off","status","tts"],source:"local",target:"local"},{name:"queue",description:"Queue a prompt for the next idle turn",category:"Session",aliases:["q"],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"yolo",description:"Toggle approval bypass",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"quit",description:"Exit herm",category:"Exit",aliases:["exit"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"stash",description:"Park the prompt (pop/list to restore)",category:"Client",aliases:[],argsHint:"[pop|list]",subcommands:["pop","list"],source:"local",target:"local"},{name:"redo",description:"Re-send the last undone message",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"branch",description:"Fork current conversation",category:"Session",aliases:["fork"],argsHint:"[name]",subcommands:[],source:"local",target:"local"},{name:"browser",description:"Connect/disconnect a CDP browser",category:"Session",aliases:[],argsHint:"[connect|disconnect|status] [url]",subcommands:["connect","disconnect","status"],source:"local",target:"local"}];function resolve10(list3,name){let q5=name.toLowerCase();for(let c of list3)if(c.name.toLowerCase()===q5||c.aliases.some((a)=>a.toLowerCase()===q5))return{hit:c};let hits=new Set;for(let c of list3)for(let n of[c.name,...c.aliases])if(n.toLowerCase().startsWith(q5)){hits.add(c);break}if(hits.size===1)return{hit:[...hits][0]};if(hits.size===0)return{miss:!0};return{ambiguous:[...hits].map((c)=>`/${c.name}`).sort()}}function matchSub(list3,input){let m2=input.match(/^\/(\w+)\s+(\S*)$/);if(!m2)return null;let name=m2[1],sub2=m2[2],cmd=list3.find((c)=>c.name===name||c.aliases.includes(name));if(!cmd||cmd.subcommands.length===0)return null;let q5=sub2.toLowerCase(),matches=cmd.subcommands.filter((s)=>s.toLowerCase().startsWith(q5));if(matches.length===0)return null;return matches.map((s)=>({...cmd,name:`${cmd.name} ${s}`,description:`${cmd.name} \u2192 ${s}`,argsHint:"",subcommands:[]}))}var CATEGORY_ORDER=["Client","Session","Configuration","Config","Tools & Skills","Skills","Plugins","MCP","Info","Exit"];function sort(list3){let idx=(c)=>{let i=CATEGORY_ORDER.indexOf(c);return i<0?999:i};return[...list3].sort((a,b2)=>{let ca=idx(a.category)-idx(b2.category);return ca!==0?ca:a.name.localeCompare(b2.name)})}var import_react114=__toESM(require_react_production(),1);var bare=(s)=>s[0]==="/"?s.slice(1):s;function useSlashCommands(){let gw=useGateway(),ready=useGatewayReady(),[cmds,setCmds]=import_react114.useState(LOCAL_COMMANDS),fetch2=import_react114.useCallback(async()=>{let res=await gw.request("commands.catalog").catch(()=>null);if(!res){setCmds(LOCAL_COMMANDS);return}let cat=new Map;for(let g of res.categories??[])for(let[n]of g.pairs??[])cat.set(bare(n),g.name);let alias=new Map,addAlias=(name,value)=>{let k2=bare(name),v2=bare(value);if(k2===v2)return;let list3=alias.get(k2)??[];if(!list3.includes(v2))alias.set(k2,[...list3,v2])};for(let l of LOCAL_COMMANDS)for(let a of l.aliases)addAlias(l.name,a);for(let[a,c]of Object.entries(res.canon??{}))addAlias(c,a);let sub2=new Map(Object.entries(res.sub??{}).map(([k2,v2])=>[bare(k2),v2])),local=new Map(LOCAL_COMMANDS.map((c)=>[c.name,c])),remote=(res.pairs??[]).map(([raw2,desc])=>{let name=bare(raw2),l=local.get(name),description=name==="quit"?desc.replace(/\s*\(usage:[^)]*\)\s*$/,""):desc;return{name,description,category:cat.get(name)??(name.includes(":")?"Skills":"Command"),aliases:alias.get(name)??[],argsHint:l?.argsHint??"",subcommands:sub2.get(name)??l?.subcommands??[],source:"command",target:LOCAL_NAMES.has(name)?"local":"gateway"}}),seen=new Set(remote.map((c)=>c.name)),locals=LOCAL_COMMANDS.filter((c)=>!seen.has(c.name));setCmds(sort([...locals,...remote]))},[gw]);return import_react114.useEffect(()=>{if(ready)fetch2()},[ready,fetch2]),{cmds,refresh:fetch2}}var import_react128=__toESM(require_react_production(),1);var import_react115=__toESM(require_react_production(),1);var GROUPS2=[{title:"Global",scope:"global"},{title:"Composer",scope:"composer"},{title:"Lists",scope:"list"},{title:"Dialogs",scope:"dialog"},{title:"Sessions",scope:"sessions"},{title:"Agents",scope:"agents"},{title:"Config",scope:"config"},{title:"Eikon",scope:"eikon"}],COLS3=2,HelpDialog=()=>{let theme=useTheme().theme,keys=useKeys(),sections2=import_react115.useMemo(()=>GROUPS2.map((g)=>({title:g.title,rows:keys.all(g.scope).filter((e)=>e.id!=="leader"&&e.chord.length>0).map((e)=>[keys.print(e.id),e.desc])})).filter((s)=>s.rows.length>0),[keys]),total=sections2.reduce((n,s)=>n+s.rows.length+2,0),split=Math.ceil(total/COLS3),cols2=[[],[]],acc2=0;for(let s of sections2){let h2=s.rows.length+2,i=acc2+h2<=split||cols2[0].length===0?0:1;if(cols2[i].push(s),i===0)acc2+=h2}return $jsxs("box",{flexDirection:"column",width:104,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:$jsx("strong",{children:"Keyboard Shortcuts"})})}),$jsx("text",{fg:theme.textMuted,children:`leader = ${keys.print("leader")}`})]}),$jsx("box",{height:1}),$jsx("box",{flexDirection:"row",gap:3,children:cols2.map((col,ci)=>$jsx("box",{flexDirection:"column",flexGrow:1,flexBasis:0,children:col.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:s.title})}),s.rows.map(([chord,desc])=>$jsxs("box",{flexDirection:"row",height:1,paddingLeft:1,children:[$jsx("box",{width:14,children:$jsx("text",{fg:theme.accent,children:chord})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:desc})})]},chord+desc))]},s.title))},ci))}),$jsx("text",{fg:theme.textMuted,children:"esc to close"})]})};var import_react116=__toESM(require_react_production(),1);import{existsSync as existsSync23,readFileSync as readFileSync17}from"fs";import{homedir as homedir7}from"os";import{join as join21}from"path";var OC_TO_HERM=[["leader","leader"],["app_exit","app.exit"],["terminal_suspend","app.suspend"],["sidebar_toggle","app.sidebar"],["command_list","palette.open"],["editor_open","editor.open"],["theme_list","theme.pick"],["model_list","model.pick"],["status_view","status.open"],["session_new","session.new"],["session_compact","session.compress"],["session_timeline","session.timeline"],["session_interrupt","session.interrupt"],["session_rename","sessions.rename"],["messages_copy","reply.copy"],["messages_redo","session.redo"],["input_clear","input.clear"],["input_submit","input.submit"],["input_newline","input.newline"],["input_paste","clipboard.attach"]],TABLE=new Map(OC_TO_HERM),ocPaths=(cwd=process.cwd())=>[join21(homedir7(),".config","opencode","tui.json"),join21(cwd,"tui.json"),join21(cwd,".opencode","tui.json"),join21(cwd,"opencode.json")],read2=(p)=>{if(!existsSync23(p))return{};return JSON.parse(readFileSync17(p,"utf8")).keybinds??{}},loadOcKeybinds=(cwd)=>{let merged={},sources=[];for(let p of ocPaths(cwd)){let kb=read2(p);if(Object.keys(kb).length===0)continue;Object.assign(merged,kb),sources.push(p)}let overrides={},skipped=[];for(let[oc,chord]of Object.entries(merged)){let herm=TABLE.get(oc);if(herm)overrides[herm]=chord;else skipped.push(oc)}return{overrides,skipped,sources}};var GROUPS3=[{title:"Global",scope:"global"},{title:"Composer",scope:"composer"},{title:"Lists",scope:"list"},{title:"Dialogs",scope:"dialog"},{title:"Sessions",scope:"sessions"},{title:"Agents",scope:"agents"},{title:"Config",scope:"config"}],KeysDialog=(props)=>{let theme=useTheme().theme,keys=useKeys(),toast=useToast(),overrides=exports_preferences.get("keys")??{},rows3=import_react116.useMemo(()=>GROUPS3.flatMap((g)=>{let entries2=keys.all(g.scope).filter((e)=>e.id!=="leader");if(entries2.length===0)return[];return[{type:"header",title:g.title},...entries2.map((e)=>({type:"action",id:e.id,desc:e.desc,chord:e.chord,override:overrides[e.id]!==void 0}))]}),[keys,overrides]),actionRows=rows3.map((r,i)=>({r,i})).filter((x2)=>x2.r.type==="action"),[sel,setSel]=import_react116.useState(0),cur=actionRows[sel]?.r,curConflicts=cur?conflictsWith(keys.table,cur.id):[],write=(id,value)=>{let next2={...exports_preferences.get("keys")??{}};if(value===void 0)delete next2[id];else next2[id]=value;exports_preferences.set("keys",next2)},rebind=(id)=>{let now2=overrides[id]??DEFAULTS2[id].chord;openTextPrompt(props.dialog,{title:`Rebind ${id}`,label:"Chord (e.g. ctrl+k, <leader>m, shift+return; empty = unbind)",initial:now2}).then((v2)=>{if(openKeys(props.dialog),v2===null)return;let parsed=parse2(v2);write(id,parsed.length===0?"none":v2)})},importOc=()=>{let r=loadOcKeybinds();if(r.sources.length===0)return toast.show({variant:"info",message:"No opencode tui.json found"});let n=Object.keys(r.overrides).length;openConfirm(props.dialog,{title:`Import ${n} keybind${n===1?"":"s"} from opencode?`,body:`${r.sources.map((s)=>`\xB7 ${s}`).join(`
|
|
4175
|
+
`;var TIERS=["block","slick","tiny"],pickFont=(innerW)=>TIERS.find((f)=>measureText({text:"HERM",font:f}).width<=innerW)??"tiny",clip=(s,w2)=>[...s].length<=w2?s:[...s].slice(0,Math.max(1,w2-1)).join("")+"\u2026";function Splash(p){let theme=useTheme().theme,ref=import_react112.useRef(null),[box2,setBox]=import_react112.useState({w:0,h:0}),renderer=useRenderer();import_react112.useEffect(()=>{let cb=async()=>{let r=ref.current;if(!r)return;setBox((b2)=>b2.w===r.width&&b2.h===r.height?b2:{w:r.width,h:r.height})};return renderer.setFrameCallback(cb),()=>renderer.removeFrameCallback(cb)},[renderer]);let{lines:lines3,inner}=import_react112.useMemo(()=>frame(box2.w,box2.h),[box2.w,box2.h]),font=import_react112.useMemo(()=>pickFont(inner.w),[inner.w]),[tip2,setTip]=import_react112.useState(()=>randomTip()),behind=p.info?.behind,sub2=[`v${VERSION}`,p.info?`hermes ${p.info.agentVersion??"?"}`:"\u2026",behind==null?null:behind===0?"up to date":`${behind} behind`,p.info?.model].filter(Boolean).join(" \xB7 "),prompt=p.last&&!p.composing,title=p.last?.title?.trim()||p.last?.id;return $jsxs("box",{ref,position:"absolute",left:0,top:0,right:0,bottom:0,zIndex:50,backgroundColor:theme.background,children:[lines3.map((l,i)=>$jsx("box",{position:"absolute",top:i,left:0,height:1,children:$jsx("text",{fg:theme.accent,children:l})},i)),lines3.length>0&&$jsxs("box",{position:"absolute",left:inner.x,top:inner.y,width:inner.w,height:inner.h,flexDirection:"column",alignItems:"center",justifyContent:"center",children:[$jsx("box",{children:$jsx("ascii-font",{text:"HERM",font,color:[theme.accent,theme.textMuted],selectable:!1})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:clip(sub2,inner.w)})}),p.news?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:clip(`\u203A ${p.news}`,inner.w)})}):null,$jsx("box",{height:2}),p.loading?$jsx("text",{fg:theme.textMuted,children:$jsx("span",{fg:theme.accent,children:"Loading\u2026"})}):prompt?$jsxs($Fragment,{children:[$jsxs("text",{fg:theme.textMuted,children:["continue ",$jsxs("span",{fg:theme.text,children:['"',clip(title??"",Math.max(8,inner.w-14)),'"']})," ?"]}),$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{fg:theme.accent,children:"[enter]"})," yes \xB7 type to start fresh"]})]}):$jsxs("text",{fg:theme.textMuted,children:[$jsx("span",{fg:theme.accent,children:"[enter]"})," to send"]}),inner.h>=14?$jsx("box",{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",alignItems:"center",onMouseDown:()=>setTip((t2)=>randomTip(t2)),children:$jsx("text",{wrapMode:"word",children:splitTip(clip(tip2,inner.w*2)).map((s,i)=>$jsx("span",{fg:s.hl?theme.accent:theme.textMuted,children:s.t},i))})}):null]})]})}init_sessions_db();function openMessage(dialog,m2,ops){let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");dialog.replace($jsx(DialogSelect,{title:"Message Actions",options:[{title:"Copy",value:"copy",description:"message text to clipboard"},{title:"Rewind here",value:"rewind",description:"undo back to this turn (destructive)"},{title:"Fork here",value:"fork",description:"branch a new session at this point"}],onSelect:(o)=>{if(dialog.clear(),o.value==="copy")return void copy(text4);if(o.value==="rewind")return ops.rewind(m2);if(o.value==="fork")return ops.fork(m2)}}))}var LOCAL_NAMES=new Set(["clear","new","theme","help","keys","logs","title","rollback","save","history","status","usage","profile","steer","reload","reload-mcp","reload-skills","chafa","splash","skin","resume","branch","compress","undo","redo","retry","model","yolo","quit","copy","paste","image","background","voice","mouse","redraw","queue","stash","compact","setup","browser"]),LOCAL_COMMANDS=[{name:"clear",description:"Clear chat messages",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"new",description:"Start a new session",category:"Client",aliases:["reset"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"theme",description:"Switch color theme or mode",category:"Client",aliases:[],argsHint:"[light|dark]",subcommands:[],source:"local",target:"local"},{name:"help",description:"Show keyboard shortcuts",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"keys",description:"Rebind keyboard shortcuts",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"logs",description:"Show gateway stderr log",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"title",description:"Set session title",category:"Client",aliases:[],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"rollback",description:"Browse & restore checkpoints",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"history",description:"Server-side transcript viewer",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"status",description:"Version, model, paths",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"usage",description:"Credits, account status, tokens, context fill, cost",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"profile",description:"Active profile details",category:"Info",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"steer",description:"Inject a note mid-turn (no interrupt)",category:"Session",aliases:[],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"reload-mcp",description:"Restart MCP servers & rediscover tools",category:"Session",aliases:[],argsHint:"[now|always]",subcommands:["now","always"],source:"local",target:"local"},{name:"reload",description:"Hot-reload ~/.hermes/.env (API keys)",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"reload-skills",description:"Re-scan ~/.hermes/skills/ for added/removed skills",category:"Session",aliases:["reload_skills"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"chafa",description:"Render image via chafa (demo)",category:"Client",aliases:[],argsHint:"<path>",subcommands:[],source:"local",target:"local"},{name:"splash",description:"Show the launch splash",category:"Client",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"goal",description:"Set/control the session goal",category:"Session",aliases:[],argsHint:"[text|done|pause|resume|clear|status]",subcommands:["done","pause","resume","clear","status"],source:"command",target:"gateway"},{name:"skin",description:"Switch Hermes skin (+ theme + eikon)",category:"Client",aliases:[],argsHint:"[name]",subcommands:[...SKINS],source:"local",target:"local"},{name:"voice",description:"Toggle voice recording",category:"Client",aliases:[],argsHint:"[on|off|status|tts]",subcommands:["on","off","status","tts"],source:"local",target:"local"},{name:"queue",description:"Queue a prompt for the next idle turn",category:"Session",aliases:["q"],argsHint:"[text]",subcommands:[],source:"local",target:"local"},{name:"yolo",description:"Toggle approval bypass",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"quit",description:"Exit herm",category:"Exit",aliases:["exit"],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"stash",description:"Park the prompt (pop/list to restore)",category:"Client",aliases:[],argsHint:"[pop|list]",subcommands:["pop","list"],source:"local",target:"local"},{name:"redo",description:"Re-send the last undone message",category:"Session",aliases:[],argsHint:"",subcommands:[],source:"local",target:"local"},{name:"branch",description:"Fork current conversation",category:"Session",aliases:["fork"],argsHint:"[name]",subcommands:[],source:"local",target:"local"},{name:"browser",description:"Connect/disconnect a CDP browser",category:"Session",aliases:[],argsHint:"[connect|disconnect|status] [url]",subcommands:["connect","disconnect","status"],source:"local",target:"local"}];function resolve10(list3,name){let q5=name.toLowerCase();for(let c of list3)if(c.name.toLowerCase()===q5||c.aliases.some((a)=>a.toLowerCase()===q5))return{hit:c};let hits=new Set;for(let c of list3)for(let n of[c.name,...c.aliases])if(n.toLowerCase().startsWith(q5)){hits.add(c);break}if(hits.size===1)return{hit:[...hits][0]};if(hits.size===0)return{miss:!0};return{ambiguous:[...hits].map((c)=>`/${c.name}`).sort()}}function matchSub(list3,input){let m2=input.match(/^\/(\w+)\s+(\S*)$/);if(!m2)return null;let name=m2[1],sub2=m2[2],cmd=list3.find((c)=>c.name===name||c.aliases.includes(name));if(!cmd||cmd.subcommands.length===0)return null;let q5=sub2.toLowerCase(),matches=cmd.subcommands.filter((s)=>s.toLowerCase().startsWith(q5));if(matches.length===0)return null;return matches.map((s)=>({...cmd,name:`${cmd.name} ${s}`,description:`${cmd.name} \u2192 ${s}`,argsHint:"",subcommands:[]}))}var CATEGORY_ORDER=["Client","Session","Configuration","Config","Tools & Skills","Skills","Plugins","MCP","Info","Exit"];function sort(list3){let idx=(c)=>{let i=CATEGORY_ORDER.indexOf(c);return i<0?999:i};return[...list3].sort((a,b2)=>{let ca=idx(a.category)-idx(b2.category);return ca!==0?ca:a.name.localeCompare(b2.name)})}var import_react114=__toESM(require_react_production(),1);var bare=(s)=>s[0]==="/"?s.slice(1):s;function useSlashCommands(){let gw=useGateway(),ready=useGatewayReady(),[cmds,setCmds]=import_react114.useState(LOCAL_COMMANDS),fetch2=import_react114.useCallback(async()=>{let res=await gw.request("commands.catalog").catch(()=>null);if(!res){setCmds(LOCAL_COMMANDS);return}let cat=new Map;for(let g of res.categories??[])for(let[n]of g.pairs??[])cat.set(bare(n),g.name);let alias=new Map,addAlias=(name,value)=>{let k2=bare(name),v2=bare(value);if(k2===v2)return;let list3=alias.get(k2)??[];if(!list3.includes(v2))alias.set(k2,[...list3,v2])};for(let l of LOCAL_COMMANDS)for(let a of l.aliases)addAlias(l.name,a);for(let[a,c]of Object.entries(res.canon??{}))addAlias(c,a);let sub2=new Map(Object.entries(res.sub??{}).map(([k2,v2])=>[bare(k2),v2])),local=new Map(LOCAL_COMMANDS.map((c)=>[c.name,c])),remote=(res.pairs??[]).map(([raw2,desc])=>{let name=bare(raw2),l=local.get(name),description=name==="quit"?desc.replace(/\s*\(usage:[^)]*\)\s*$/,""):desc;return{name,description,category:cat.get(name)??(name.includes(":")?"Skills":"Command"),aliases:alias.get(name)??[],argsHint:l?.argsHint??"",subcommands:sub2.get(name)??l?.subcommands??[],source:"command",target:LOCAL_NAMES.has(name)?"local":"gateway"}}),seen=new Set(remote.map((c)=>c.name)),locals=LOCAL_COMMANDS.filter((c)=>!seen.has(c.name));setCmds(sort([...locals,...remote]))},[gw]);return import_react114.useEffect(()=>{if(ready)fetch2()},[ready,fetch2]),{cmds,refresh:fetch2}}var import_react128=__toESM(require_react_production(),1);var import_react115=__toESM(require_react_production(),1);var GROUPS2=[{title:"Global",scope:"global"},{title:"Composer",scope:"composer"},{title:"Lists",scope:"list"},{title:"Dialogs",scope:"dialog"},{title:"Sessions",scope:"sessions"},{title:"Agents",scope:"agents"},{title:"Config",scope:"config"},{title:"Eikon",scope:"eikon"}],COLS3=2,HelpDialog=()=>{let theme=useTheme().theme,keys=useKeys(),sections2=import_react115.useMemo(()=>GROUPS2.map((g)=>({title:g.title,rows:keys.all(g.scope).filter((e)=>e.id!=="leader"&&e.chord.length>0).map((e)=>[keys.print(e.id),e.desc])})).filter((s)=>s.rows.length>0),[keys]),total=sections2.reduce((n,s)=>n+s.rows.length+2,0),split=Math.ceil(total/COLS3),cols2=[[],[]],acc2=0;for(let s of sections2){let h2=s.rows.length+2,i=acc2+h2<=split||cols2[0].length===0?0:1;if(cols2[i].push(s),i===0)acc2+=h2}return $jsxs("box",{flexDirection:"column",width:104,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:$jsx("strong",{children:"Keyboard Shortcuts"})})}),$jsx("text",{fg:theme.textMuted,children:`leader = ${keys.print("leader")}`})]}),$jsx("box",{height:1}),$jsx("box",{flexDirection:"row",gap:3,children:cols2.map((col,ci)=>$jsx("box",{flexDirection:"column",flexGrow:1,flexBasis:0,children:col.map((s)=>$jsxs("box",{flexDirection:"column",marginBottom:1,children:[$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:s.title})}),s.rows.map(([chord,desc])=>$jsxs("box",{flexDirection:"row",height:1,paddingLeft:1,children:[$jsx("box",{width:14,children:$jsx("text",{fg:theme.accent,children:chord})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:desc})})]},chord+desc))]},s.title))},ci))}),$jsx("text",{fg:theme.textMuted,children:"esc to close"})]})};var import_react116=__toESM(require_react_production(),1);import{existsSync as existsSync24,readFileSync as readFileSync17}from"fs";import{homedir as homedir7}from"os";import{join as join21}from"path";var OC_TO_HERM=[["leader","leader"],["app_exit","app.exit"],["terminal_suspend","app.suspend"],["sidebar_toggle","app.sidebar"],["command_list","palette.open"],["editor_open","editor.open"],["theme_list","theme.pick"],["model_list","model.pick"],["status_view","status.open"],["session_new","session.new"],["session_compact","session.compress"],["session_timeline","session.timeline"],["session_interrupt","session.interrupt"],["session_rename","sessions.rename"],["messages_copy","reply.copy"],["messages_redo","session.redo"],["input_clear","input.clear"],["input_submit","input.submit"],["input_newline","input.newline"],["input_paste","clipboard.attach"]],TABLE=new Map(OC_TO_HERM),ocPaths=(cwd=process.cwd())=>[join21(homedir7(),".config","opencode","tui.json"),join21(cwd,"tui.json"),join21(cwd,".opencode","tui.json"),join21(cwd,"opencode.json")],read2=(p)=>{if(!existsSync24(p))return{};return JSON.parse(readFileSync17(p,"utf8")).keybinds??{}},loadOcKeybinds=(cwd)=>{let merged={},sources=[];for(let p of ocPaths(cwd)){let kb=read2(p);if(Object.keys(kb).length===0)continue;Object.assign(merged,kb),sources.push(p)}let overrides={},skipped=[];for(let[oc,chord]of Object.entries(merged)){let herm=TABLE.get(oc);if(herm)overrides[herm]=chord;else skipped.push(oc)}return{overrides,skipped,sources}};var GROUPS3=[{title:"Global",scope:"global"},{title:"Composer",scope:"composer"},{title:"Lists",scope:"list"},{title:"Dialogs",scope:"dialog"},{title:"Sessions",scope:"sessions"},{title:"Agents",scope:"agents"},{title:"Config",scope:"config"}],KeysDialog=(props)=>{let theme=useTheme().theme,keys=useKeys(),toast=useToast(),overrides=exports_preferences.get("keys")??{},rows3=import_react116.useMemo(()=>GROUPS3.flatMap((g)=>{let entries2=keys.all(g.scope).filter((e)=>e.id!=="leader");if(entries2.length===0)return[];return[{type:"header",title:g.title},...entries2.map((e)=>({type:"action",id:e.id,desc:e.desc,chord:e.chord,override:overrides[e.id]!==void 0}))]}),[keys,overrides]),actionRows=rows3.map((r,i)=>({r,i})).filter((x2)=>x2.r.type==="action"),[sel,setSel]=import_react116.useState(0),cur=actionRows[sel]?.r,curConflicts=cur?conflictsWith(keys.table,cur.id):[],write=(id,value)=>{let next2={...exports_preferences.get("keys")??{}};if(value===void 0)delete next2[id];else next2[id]=value;exports_preferences.set("keys",next2)},rebind=(id)=>{let now2=overrides[id]??DEFAULTS2[id].chord;openTextPrompt(props.dialog,{title:`Rebind ${id}`,label:"Chord (e.g. ctrl+k, <leader>m, shift+return; empty = unbind)",initial:now2}).then((v2)=>{if(openKeys(props.dialog),v2===null)return;let parsed=parse2(v2);write(id,parsed.length===0?"none":v2)})},importOc=()=>{let r=loadOcKeybinds();if(r.sources.length===0)return toast.show({variant:"info",message:"No opencode tui.json found"});let n=Object.keys(r.overrides).length;openConfirm(props.dialog,{title:`Import ${n} keybind${n===1?"":"s"} from opencode?`,body:`${r.sources.map((s)=>`\xB7 ${s}`).join(`
|
|
4174
4176
|
`)}
|
|
4175
4177
|
|
|
4176
4178
|
${n} mapped \xB7 ${r.skipped.length} skipped (no herm equivalent)${r.skipped.length?`:
|
|
4177
4179
|
${r.skipped.slice(0,8).join(", ")}${r.skipped.length>8?", \u2026":""}`:""}`,yes:"import"}).then((ok)=>{if(openKeys(props.dialog),!ok)return;exports_preferences.set("keys",{...exports_preferences.get("keys")??{},...r.overrides}),toast.show({variant:"success",message:`Imported ${n} \xB7 skipped ${r.skipped.length}`})})};return useKeyboard((key4)=>{if(key4.name==="up")return setSel((s)=>Math.max(0,s-1));if(key4.name==="down")return setSel((s)=>Math.min(actionRows.length-1,s+1));if(key4.name==="return"&&cur)return rebind(cur.id);if(key4.name==="r"&&!key4.ctrl&&cur?.override){write(cur.id,void 0);return}if(key4.name==="o"&&!key4.ctrl)return importOc()}),$jsxs("box",{flexDirection:"column",width:78,children:[$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:$jsx("strong",{children:"Keybindings"})})}),$jsx("text",{fg:theme.textMuted,children:`leader = ${keys.print("leader")}`})]}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,maxHeight:22,verticalScrollbarOptions:VBAR,children:$jsx("box",{flexDirection:"column",width:"100%",children:rows3.map((r,i)=>{if(r.type==="header")return $jsx("box",{height:1,marginTop:i>0?1:0,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:r.title})})},`h-${r.title}`);let ai=actionRows.findIndex((x2)=>x2.i===i),on=ai===sel,conf=conflictsWith(keys.table,r.id);return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:on?theme.backgroundElement:void 0,onMouseOver:()=>setSel(ai),onMouseDown:()=>{setSel(ai),rebind(r.id)},children:[$jsx("box",{width:2,flexShrink:0,children:$jsx("text",{fg:on?theme.primary:theme.text,children:on?"\u25B8 ":" "})}),$jsx("box",{width:16,flexShrink:0,height:1,overflow:"hidden",children:$jsx("text",{fg:on?theme.accent:theme.text,children:print(r.chord,keys.print("leader"))||"\u2014"})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,children:r.desc})}),$jsx("box",{width:5,flexShrink:0,flexDirection:"row",justifyContent:"flex-end",children:$jsxs("text",{children:[r.override?$jsx("span",{fg:theme.info,children:"\xB7 "}):null,conf.length>0?$jsx("span",{fg:theme.warning,children:"\u26A0"}):null]})})]},r.id)})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:curConflicts.length>0?$jsx("text",{fg:theme.warning,children:`\u26A0 shares ${keys.print(cur.id)} with: ${curConflicts.join(", ")}`}):$jsx("text",{fg:theme.textMuted,children:`\u2191\u2193 select Enter rebind${cur?.override?" \xB7 r reset":""} \xB7 o import opencode \xB7 esc close \xB7 \xB7 = overridden`})})]})};function openKeys(dialog){dialog.replace($jsx(KeysDialog,{dialog}))}var ERRLIKE=/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i,LogsDialog=()=>{let theme=useTheme().theme,lines3=useGateway().tail(200).split(`
|
|
4178
|
-
`).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines3.length+5)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Gateway Logs"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[lines3.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines3.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No log output captured."})}):$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",children:lines3.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:ERRLIKE.test(l)?theme.error:theme.textMuted,children:l.length>106?l.slice(0,105)+"\u2026":l})},i))})})]})},openLogs=(dialog)=>dialog.replace($jsx(LogsDialog,{}));var import_react118=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react118.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react118.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]),flip=import_react118.useCallback(()=>{ctx.setMode(ctx.mode==="dark"?"light":"dark")},[ctx]),onKey=import_react118.useCallback((key4)=>{if(key4.name!=="tab")return!1;return flip(),!0},[flip]),footer=$jsx("box",{height:1,onMouseDown:flip,children:$jsxs("text",{fg:ctx.theme.textMuted,children:[$jsx("span",{children:"Mode: "}),$jsx("span",{fg:ctx.mode==="light"?ctx.theme.warning:ctx.theme.accent,children:ctx.mode}),$jsx("span",{children:" \xB7 Tab/click: toggle"})]})});return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,onKey,placeholder:"Search themes...",footer})},openThemePicker=(dialog,ctx)=>{let{name:saved,mode}=ctx,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(confirmed)return;ctx.set(saved),ctx.setMode(mode)})};var import_react119=__toESM(require_react_production(),1);import{homedir as homedir8}from"os";import{join as join22}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join22(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join22(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs=props.dirs??defaultDirs(),found=import_react119.useMemo(()=>listEikons(dirs),[dirs]),[cursor,setCursor]=import_react119.useState(0),cur=found[cursor],parsed=import_react119.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]);useListKeys({active:!0,count:found.length,setSel:setCursor,onActivate:()=>{if(cur)props.onSelect(cur.meta.name.toLowerCase()),dialog.clear()}});let w2=(parsed?.meta.width??48)+2,h2=Math.max(parsed?.meta.height??24,12);return $jsxs("box",{flexDirection:"column",width:40+w2,height:h2+4,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Pick Avatar"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${found.length} found \xB7 \u2191\u2193 nav \xB7 Enter select \xB7 Esc close`})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx("box",{width:38,marginRight:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:found.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found.map((e,i)=>{let on=i===cursor;return $jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>setCursor(i),children:[$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:$jsx("strong",{children:trunc6(e.meta.name,34)})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${e.meta.author??"\u2014"} \xB7 ${e.meta.states.length} states`})})]},e.path)})})})}),$jsx("box",{flexGrow:1,flexDirection:"column",overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur?.path??"none"):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No preview."})},"blank")})]})]})},openEikonPicker=(dialog,onSelect)=>dialog.replace($jsx(EikonPickerDialog,{onSelect}));var import_react120=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react120.useState(props.initial??null),[sel,setSel]=import_react120.useState(props.sel??0),[diff,setDiff]=import_react120.useState(null),[confirm,setConfirm]=import_react120.useState(!1);import_react120.useEffect(()=>{if(props.initial)return;props.gw.request("rollback.list").then(setData).catch((e)=>setData({enabled:!1,checkpoints:[],...{err:e.message}}))},[props.gw,props.initial]);let points=data2?.checkpoints??[],cur=points[sel],open2=(cp)=>{props.gw.request("rollback.diff",{hash:cp.hash}).then(setDiff).catch((e)=>props.toast.error(e))},back=()=>{setDiff(null),setConfirm(!1),props.dialog.replace($jsx(RollbackDialog,{gw:props.gw,toast:props.toast,dialog:props.dialog,initial:data2??void 0,sel}))},restore=(cp)=>{props.gw.request("rollback.restore",{hash:cp.hash}).then((r)=>{if(!r.success)throw Error("restore rejected");let n=r.history_removed;props.toast.show({variant:"success",message:`Restored ${cp.hash.slice(0,7)}${n?` \xB7 ${n} turns removed`:""}`}),props.dialog.clear()}).catch((e)=>{props.toast.show({variant:"error",message:`Restore failed: ${e.message}`}),props.dialog.clear()})},keys=useKeys();if(useKeyboard((key4)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key4))return restore(cur);if(keys.match("dialog.deny",key4)||keys.match("dialog.cancel",key4))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key4))return back();if(key4.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key4,{count:points.length,setSel,onActivate:()=>{if(cur)open2(cur)}})}),!data2)return $jsx("box",{width:60,height:3,children:$jsx("text",{fg:theme.textMuted,children:"Loading checkpoints\u2026"})});if(!data2.enabled)return $jsxs("box",{flexDirection:"column",width:60,height:5,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Checkpoints disabled"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enable checkpoints in config to use /rollback."})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to close"})})]});if(diff){let body=diff.rendered||diff.diff||diff.stat||"(empty diff)";return $jsxs("box",{flexDirection:"column",width:110,height:30,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Rollback \xB7 "})}),$jsx("span",{fg:theme.accent,children:cur.hash.slice(0,7)}),$jsx("span",{fg:theme.textMuted,children:` ${trunc5(cur.message,70)}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:diff.stat||" "})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx(DiffBlock,{text:body})})}),$jsx("box",{height:1}),confirm?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.warning,children:$jsx("strong",{children:"Restore this checkpoint? "})}),$jsx("span",{fg:theme.textMuted,children:"[y] restore [n] cancel"})]})}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[r] restore \xB7 Esc back"})})]})}return $jsxs("box",{flexDirection:"column",width:90,height:Math.min(28,Math.max(8,points.length+6)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Rollback"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${points.length} checkpoints \xB7 \u2191\u2193 navigate Enter diff Esc close`})}),$jsx("box",{height:1}),points.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No checkpoints yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:points.map((cp,i)=>{let on=i===sel;return $jsx("box",{height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),open2(cp)},onMouseOver:()=>setSel(i),children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx("span",{fg:theme.accent,children:cp.hash.slice(0,7).padEnd(9)}),$jsx("span",{fg:theme.textMuted,children:ago(cp.timestamp).padEnd(12)}),$jsx("span",{fg:on?theme.text:theme.textMuted,children:trunc5(cp.message,56)})]})},cp.hash)})})})]})},openRollback=(dialog,gw,toast)=>dialog.replace($jsx(RollbackDialog,{gw,toast,dialog}));var import_react122=__toESM(require_react_production(),1);var tag=(m2,theme)=>m2.role==="user"?{label:"\u25B8 You",fg:theme.info}:m2.role==="assistant"?{label:"\u25C2 Agent",fg:theme.success}:m2.role==="tool"?{label:`\u2699 ${m2.name??"tool"}`,fg:theme.warning}:{label:"\xB7 system",fg:theme.textMuted},flatten2=(t2)=>{if(typeof t2==="string")return t2;if(!Array.isArray(t2))return"";for(let p of t2)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")return p.text;return""},body=(m2)=>m2.role==="tool"?m2.context??"":flatten2(m2.text),HistoryDialog=(props)=>{let theme=useTheme().theme,[rows3,setRows]=import_react122.useState(null),[err,setErr]=import_react122.useState("");import_react122.useEffect(()=>{props.gw.request("session.history").then((r)=>setRows(r.messages??[])).catch((e)=>{setErr(e.message),setRows([])})},[props.gw]);let n=rows3?.length??0,h2=Math.min(34,Math.max(8,n+5));return $jsxs("box",{flexDirection:"column",width:110,height:h2,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Session History"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:err?theme.error:theme.textMuted,children:err?`\u26A0 ${err}`:`${n} messages \xB7 server-authoritative \xB7 Esc to close`})}),$jsx("box",{height:1}),rows3===null?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading\u2026"})}):n===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Empty \u2014 no turns yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((m2,i)=>{let t2=tag(m2,theme);return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:t2.fg,children:trunc5(t2.label,13)})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:m2.role==="tool"||m2.role==="system"?theme.textMuted:theme.text,children:body(m2).replace(/\n/g," ")})})]},i)})})})]})},openHistory=(dialog,gw)=>dialog.replace($jsx(HistoryDialog,{gw}));var import_react123=__toESM(require_react_production(),1);var InfoDialog=(props)=>{let theme=useTheme().theme,body2=props.rows.filter((r)=>r[1]!==void 0);return $jsxs("box",{flexDirection:"column",minWidth:52,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),props.lines?.length?$jsx("box",{flexDirection:"column",children:props.lines.map((line4,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.text,children:line4})},i))}):null,$jsx("box",{flexDirection:"column",children:$jsx(KVBlock,{rows:body2})}),props.note?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.note})}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"Esc to close"})})]})};function openStatus(dialog,info2,sid2){let toolsets=Object.keys(info2?.tools??{}),nTools=Object.values(info2?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info2?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info2?.version||"\u2014"],["Model",info2?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info2?.cwd||process.cwd()],["Session",sid2||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info2?.skills??{}).reduce((n,v2)=>n+v2.length,0))],["MCP",mcp.length?`${up}/${mcp.length} connected`:void 0]]}))}var UsageDialog=({gw})=>{let theme=useTheme().theme,[u3,setU]=import_react123.useState(null),[err,setErr]=import_react123.useState("");if(import_react123.useEffect(()=>{gw.request("session.usage").then(setU).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]),err)return $jsx(InfoDialog,{title:"Usage",rows:[["Error",err,theme.error]]});if(!u3)return $jsx(InfoDialog,{title:"Usage",rows:[["","\u2026"]]});let ctx=u3.context_max?`${fmt(u3.context_used??0)} / ${fmt(u3.context_max)} (${Math.round(u3.context_percent??0)}%)`:void 0;return $jsx(InfoDialog,{title:"Usage",lines:u3.credits_lines,note:u3.cost_status==="estimated"?"cost is estimated":void 0,rows:[["Model",u3.model||"\u2014"],["API calls",String(u3.calls??0)],["Input",fmt(u3.input??0)],["Output",fmt(u3.output??0)],["Cache r/w",u3.cache_read||u3.cache_write?`${fmt(u3.cache_read??0)} / ${fmt(u3.cache_write??0)}`:void 0],["Reasoning",u3.reasoning?fmt(u3.reasoning):void 0],["Total",fmt(u3.total??0)],["Context",ctx],["Cost",u3.cost_usd!=null?cost2(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react123.useState(void 0),active=activeProfileName();if(import_react123.useEffect(()=>{listProfiles().then((ps)=>setP(ps.find((x2)=>x2.name===active)??null)).catch(()=>setP(null))},[]),p===void 0)return $jsx(InfoDialog,{title:"Profile",rows:[["","\u2026"]]});return $jsx(InfoDialog,{title:"Profile",note:p?void 0:"profile directory not found",rows:[["Active",active],["Home",p?.path??hermesPath("")],["Model",p?.model??"\u2014"],["Provider",p?.provider??"\u2014"],["Skills",p?String(p.skill_count):void 0],["Gateway",p?.gateway_running?"running":"stopped"],["Sticky",p?.is_sticky?"yes":void 0],["Alias",p?.is_default?void 0:p?.has_alias?`~/.local/bin/${active}`:"\u2014"],[".env",p?.has_env?"present":"\u2014"]]})},openProfile=(dialog)=>dialog.replace($jsx(ProfileDialog,{}));var import_react124=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync24}from"fs";var CHAFA=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa"];function whichChafa(){for(let p of CHAFA)if(existsSync24(p))return p;return null}function render(path7,w2,h2){let bin=whichChafa();if(!bin)return{err:"chafa not installed (brew/apt install chafa)"};let full=path7.startsWith("~")?path7.replace(/^~/,process.env.HOME??""):path7;if(!existsSync24(full))return{err:`file not found: ${full}`};let r=spawnSync3(bin,[`--size=${w2}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8"});if(r.status!==0)return{err:r.stderr||`chafa exit ${r.status}`};return{rows:parseChafa(r.stdout)}}var ChafaDialog=({path:path7})=>{let theme=useTheme().theme,[w2]=import_react124.useState(80),[h2]=import_react124.useState(28),result=import_react124.useMemo(()=>render(path7,w2,h2),[path7,w2,h2]);return $jsxs("box",{flexDirection:"column",minWidth:w2+4,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsxs("strong",{children:["chafa demo \xB7 ",path7]})})}),result.err?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:result.err})}):$jsx("box",{flexDirection:"column",children:result.rows.map((row4,i)=>$jsx("text",{children:row4.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.borderSubtle,children:[result.rows?`${result.rows.length} rows \xB7 ${result.rows.reduce((a,r)=>a+r.length,0)} cells \xB7 `:"","Esc to close"]})})]})};function openChafa(dialog,path7){dialog.replace($jsx(ChafaDialog,{path:path7}))}var import_react126=__toESM(require_react_production(),1);import{tmpdir as tmpdir4}from"os";import{join as join23}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path7=join23(tmpdir4(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text4=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text4.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text4.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key4,Selection:()=>exports_selection});function yank(renderer,toast){let text4=renderer.getSelection()?.getSelectedText();if(!text4)return!1;return copy(text4).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key4(renderer,evt,toast){let sel=renderer.getSelection();if(!sel?.getSelectedText())return!1;if(evt.ctrl&&evt.name==="c")return yank(renderer,toast),!0;if(evt.name==="escape")return renderer.clearSelection(),!0;let focus=renderer.currentFocusedRenderable;if(focus&&sel.selectedRenderables.includes(focus))return!1;return renderer.clearSelection(),!1}var SGR_MOUSE_BLOB_RE=/^(?:\x1b\[|\^\[\[)?<?\d+(?:;\d+){1,2}[Mm]$/,SGR_MOUSE_RESIDUE_RE=/^\d+(?:;\d+){1,2}[Mm]$/;function isDegradedMouseInput(key5){return[key5.raw,key5.sequence,key5.name].some((v2)=>typeof v2==="string"&&isDegradedMouseBlob(v2))}function isDegradedMouseBlob(text4){if(!text4||/\s/.test(text4))return!1;return SGR_MOUSE_BLOB_RE.test(text4)||SGR_MOUSE_RESIDUE_RE.test(text4)}var DEFAULT_VOICE_KEY={mod:"ctrl",ch:"b",raw:"ctrl+b"},MOD_ALIASES={alt:"alt",ctrl:"ctrl",control:"ctrl",option:"alt",opt:"alt"};function parseVoiceRecordKey(raw2){if(typeof raw2!=="string"||!raw2.trim())return DEFAULT_VOICE_KEY;let lower=raw2.trim().toLowerCase(),parts2=lower.split("+").map((p)=>p.trim()).filter(Boolean);if(parts2.length<2)return DEFAULT_VOICE_KEY;if(parts2.length>2)return DEFAULT_VOICE_KEY;let[modRaw,chRaw]=parts2,mod=MOD_ALIASES[modRaw];if(!mod)return DEFAULT_VOICE_KEY;if(chRaw.length!==1)return DEFAULT_VOICE_KEY;if(mod==="ctrl"&&(chRaw==="c"||chRaw==="d"||chRaw==="l"))return DEFAULT_VOICE_KEY;return{mod,ch:chRaw,raw:lower}}function formatVoiceRecordKey(v2){return`${v2.mod[0].toUpperCase()+v2.mod.slice(1)}+${v2.ch.toUpperCase()}`}function isVoiceToggleKey(key5,configured2=DEFAULT_VOICE_KEY){if(key5.name.toLowerCase()!==configured2.ch)return!1;if(key5.shift)return!1;switch(configured2.mod){case"ctrl":return key5.ctrl&&!key5.meta&&!key5.super;case"alt":return key5.meta&&!key5.ctrl&&!key5.super}}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400,QUIT_MS=2000;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react126.useRef(0),lastTab=import_react126.useRef(0),lastQuit=import_react126.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react126.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key5)=>{let c=o.composer.current;if(isDegradedMouseInput(key5)){key5.stopPropagation();return}if(exports_selection.key(renderer,key5)){key5.stopPropagation();return}if(keys.match("input.clear",key5)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key5.stopPropagation();return}if(keys.match("input.stash",key5)){o.onStash(),key5.stopPropagation();return}if(keys.match("app.exit",key5)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key5.stopPropagation();return}if(keys.match("app.suspend",key5)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key5)){redraw(renderer),key5.stopPropagation();return}if(keys.match("app.sidebar",key5)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key5,o.voiceRecordKey)){o.onVoiceRecord(),key5.stopPropagation();return}if(c?.mode()==="shell"){if(key5.name==="escape"){c.setMode("normal"),key5.stopPropagation();return}if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c.caret()===0){c.setMode("normal"),key5.stopPropagation();return}}if(keys.match("session.steer",key5)){o.onSteer(),key5.stopPropagation();return}if(keys.match("queue.flush",key5)&&o.streaming&&o.queued>0){o.onFlushQueue(),key5.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(o.onPromptKey(key5)){key5.stopPropagation();return}}if(keys.match("editor.open",key5)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key5)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key5)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key5.shift&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name==="left"){o.cycleSub(-1),key5.stopPropagation();return}if(key5.name==="right"){o.cycleSub(1),key5.stopPropagation();return}}if(keys.leader&&!key5.ctrl&&!key5.meta&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(key5.meta&&!key5.ctrl&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(c?.popOpen()){if(key5.name==="escape")return c.popCancel();if(key5.name==="up"){c.popNav(-1),key5.stopPropagation();return}if(key5.name==="down"){c.popNav(1),key5.stopPropagation();return}if(key5.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key5)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key5.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key5)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key5))return o.onCopyLast();if(keys.match("clipboard.attach",key5)){o.onAttachClipboard(),key5.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key5.name==="!"||key5.name==="1"&&key5.shift)&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key5.stopPropagation();return}if(key5.name==="up")return void c?.historyUp();if(key5.name==="down")return void c?.historyDown();if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c?.isEmpty()&&o.onDetachLast()){key5.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name.length===1&&key5.name!==" "){let ch=key5.shift&&/[a-z]/.test(key5.name)?key5.name.toUpperCase():key5.name;o.setFocusRegion("input"),c?.insert(ch),key5.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid2,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid2?`
|
|
4180
|
+
`).filter(Boolean);return $jsxs("box",{flexDirection:"column",width:110,height:Math.min(34,Math.max(8,lines3.length+5)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Gateway Logs"})})}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.textMuted,children:[lines3.length," lines \xB7 stderr + protocol \xB7 Esc to close"]})}),$jsx("box",{height:1}),lines3.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No log output captured."})}):$jsx("scrollbox",{scrollY:!0,stickyScroll:!0,stickyStart:"bottom",flexGrow:1,children:$jsx("box",{flexDirection:"column",children:lines3.map((l,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:ERRLIKE.test(l)?theme.error:theme.textMuted,children:l.length>106?l.slice(0,105)+"\u2026":l})},i))})})]})},openLogs=(dialog)=>dialog.replace($jsx(LogsDialog,{}));var import_react118=__toESM(require_react_production(),1);var ThemePickerDialog=({onConfirm})=>{let ctx=useTheme(),dialog=useDialog(),options=ctx.names.map((n)=>({title:n,value:n})),onMove=import_react118.useCallback((opt)=>{ctx.set(opt.value)},[ctx]),onSelect=import_react118.useCallback((opt)=>{ctx.set(opt.value),onConfirm(),dialog.clear()},[ctx,dialog,onConfirm]),flip=import_react118.useCallback(()=>{ctx.setMode(ctx.mode==="dark"?"light":"dark")},[ctx]),onKey=import_react118.useCallback((key4)=>{if(key4.name!=="tab")return!1;return flip(),!0},[flip]),footer=$jsx("box",{height:1,onMouseDown:flip,children:$jsxs("text",{fg:ctx.theme.textMuted,children:[$jsx("span",{children:"Mode: "}),$jsx("span",{fg:ctx.mode==="light"?ctx.theme.warning:ctx.theme.accent,children:ctx.mode}),$jsx("span",{children:" \xB7 Tab/click: toggle"})]})});return $jsx(DialogSelect,{title:"Switch Theme",options,current:ctx.name,onSelect,onMove,onKey,placeholder:"Search themes...",footer})},openThemePicker=(dialog,ctx)=>{let{name:saved,mode}=ctx,confirmed=!1;dialog.replace($jsx(ThemePickerDialog,{onConfirm:()=>{confirmed=!0}}),()=>{if(confirmed)return;ctx.set(saved),ctx.setMode(mode)})};var import_react119=__toESM(require_react_production(),1);import{homedir as homedir8}from"os";import{join as join22}from"path";var trunc6=(s,n)=>s.length<=n?s:s.slice(0,n-1)+"\u2026",defaultDirs=()=>{let hermesHome2=process.env.HERMES_HOME||join22(homedir8(),".hermes");return[BUNDLED_EIKON_DIR,join22(hermesHome2,"eikons")]},EikonPickerDialog=(props)=>{let theme=useTheme().theme,dialog=useDialog(),dirs=props.dirs??defaultDirs(),found=import_react119.useMemo(()=>listEikons(dirs),[dirs]),[cursor,setCursor]=import_react119.useState(0),cur=found[cursor],parsed=import_react119.useMemo(()=>{if(!cur)return;try{return parseEikonFile(cur.path)}catch{return}},[cur]);useListKeys({active:!0,count:found.length,setSel:setCursor,onActivate:()=>{if(cur)props.onSelect(cur.meta.name.toLowerCase()),dialog.clear()}});let w2=(parsed?.meta.width??48)+2,h2=Math.max(parsed?.meta.height??24,12);return $jsxs("box",{flexDirection:"column",width:40+w2,height:h2+4,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Pick Avatar"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${found.length} found \xB7 \u2191\u2193 nav \xB7 Enter select \xB7 Esc close`})}),$jsx("box",{height:1}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsx("box",{width:38,marginRight:2,children:$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:found.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No .eikon files found."})},"empty"):found.map((e,i)=>{let on=i===cursor;return $jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>setCursor(i),children:[$jsx("box",{height:1,children:$jsx("text",{fg:on?theme.text:theme.textMuted,children:$jsx("strong",{children:trunc6(e.meta.name,34)})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${e.meta.author??"\u2014"} \xB7 ${e.meta.states.length} states`})})]},e.path)})})})}),$jsx("box",{flexGrow:1,flexDirection:"column",overflow:"hidden",children:parsed?$jsx(AnimatedAvatar,{state:"idle",eikon:parsed},cur?.path??"none"):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No preview."})},"blank")})]})]})},openEikonPicker=(dialog,onSelect)=>dialog.replace($jsx(EikonPickerDialog,{onSelect}));var import_react120=__toESM(require_react_production(),1);var RollbackDialog=(props)=>{let theme=useTheme().theme,[data2,setData]=import_react120.useState(props.initial??null),[sel,setSel]=import_react120.useState(props.sel??0),[diff,setDiff]=import_react120.useState(null),[confirm,setConfirm]=import_react120.useState(!1);import_react120.useEffect(()=>{if(props.initial)return;props.gw.request("rollback.list").then(setData).catch((e)=>setData({enabled:!1,checkpoints:[],...{err:e.message}}))},[props.gw,props.initial]);let points=data2?.checkpoints??[],cur=points[sel],open2=(cp)=>{props.gw.request("rollback.diff",{hash:cp.hash}).then(setDiff).catch((e)=>props.toast.error(e))},back=()=>{setDiff(null),setConfirm(!1),props.dialog.replace($jsx(RollbackDialog,{gw:props.gw,toast:props.toast,dialog:props.dialog,initial:data2??void 0,sel}))},restore=(cp)=>{props.gw.request("rollback.restore",{hash:cp.hash}).then((r)=>{if(!r.success)throw Error("restore rejected");let n=r.history_removed;props.toast.show({variant:"success",message:`Restored ${cp.hash.slice(0,7)}${n?` \xB7 ${n} turns removed`:""}`}),props.dialog.clear()}).catch((e)=>{props.toast.show({variant:"error",message:`Restore failed: ${e.message}`}),props.dialog.clear()})},keys=useKeys();if(useKeyboard((key4)=>{if(diff){if(confirm){if(keys.match("dialog.confirm",key4))return restore(cur);if(keys.match("dialog.deny",key4)||keys.match("dialog.cancel",key4))return setConfirm(!1),back();return}if(keys.match("dialog.cancel",key4))return back();if(key4.name==="r")return setConfirm(!0);return}if(!data2?.enabled)return;handleListKey(keys,key4,{count:points.length,setSel,onActivate:()=>{if(cur)open2(cur)}})}),!data2)return $jsx("box",{width:60,height:3,children:$jsx("text",{fg:theme.textMuted,children:"Loading checkpoints\u2026"})});if(!data2.enabled)return $jsxs("box",{flexDirection:"column",width:60,height:5,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:"Checkpoints disabled"})})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Enable checkpoints in config to use /rollback."})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Esc to close"})})]});if(diff){let body=diff.rendered||diff.diff||diff.stat||"(empty diff)";return $jsxs("box",{flexDirection:"column",width:110,height:30,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.primary,children:$jsx("strong",{children:"Rollback \xB7 "})}),$jsx("span",{fg:theme.accent,children:cur.hash.slice(0,7)}),$jsx("span",{fg:theme.textMuted,children:` ${trunc5(cur.message,70)}`})]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:diff.stat||" "})}),$jsx("box",{height:1}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:$jsx(DiffBlock,{text:body})})}),$jsx("box",{height:1}),confirm?$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.warning,children:$jsx("strong",{children:"Restore this checkpoint? "})}),$jsx("span",{fg:theme.textMuted,children:"[y] restore [n] cancel"})]})}):$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"[r] restore \xB7 Esc back"})})]})}return $jsxs("box",{flexDirection:"column",width:90,height:Math.min(28,Math.max(8,points.length+6)),children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Rollback"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:`${points.length} checkpoints \xB7 \u2191\u2193 navigate Enter diff Esc close`})}),$jsx("box",{height:1}),points.length===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"No checkpoints yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",width:"100%",children:points.map((cp,i)=>{let on=i===sel;return $jsx("box",{height:1,backgroundColor:on?theme.backgroundElement:void 0,onMouseDown:()=>{setSel(i),open2(cp)},onMouseOver:()=>setSel(i),children:$jsxs("text",{children:[$jsx("span",{fg:on?theme.primary:theme.textMuted,children:on?"\u25B8 ":" "}),$jsx("span",{fg:theme.accent,children:cp.hash.slice(0,7).padEnd(9)}),$jsx("span",{fg:theme.textMuted,children:ago(cp.timestamp).padEnd(12)}),$jsx("span",{fg:on?theme.text:theme.textMuted,children:trunc5(cp.message,56)})]})},cp.hash)})})})]})},openRollback=(dialog,gw,toast)=>dialog.replace($jsx(RollbackDialog,{gw,toast,dialog}));var import_react122=__toESM(require_react_production(),1);var tag=(m2,theme)=>m2.role==="user"?{label:"\u25B8 You",fg:theme.info}:m2.role==="assistant"?{label:"\u25C2 Agent",fg:theme.success}:m2.role==="tool"?{label:`\u2699 ${m2.name??"tool"}`,fg:theme.warning}:{label:"\xB7 system",fg:theme.textMuted},flatten2=(t2)=>{if(typeof t2==="string")return t2;if(!Array.isArray(t2))return"";for(let p of t2)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")return p.text;return""},body=(m2)=>m2.role==="tool"?m2.context??"":flatten2(m2.text),HistoryDialog=(props)=>{let theme=useTheme().theme,[rows3,setRows]=import_react122.useState(null),[err,setErr]=import_react122.useState("");import_react122.useEffect(()=>{props.gw.request("session.history").then((r)=>setRows(r.messages??[])).catch((e)=>{setErr(e.message),setRows([])})},[props.gw]);let n=rows3?.length??0,h2=Math.min(34,Math.max(8,n+5));return $jsxs("box",{flexDirection:"column",width:110,height:h2,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:"Session History"})})}),$jsx("box",{height:1,children:$jsx("text",{fg:err?theme.error:theme.textMuted,children:err?`\u26A0 ${err}`:`${n} messages \xB7 server-authoritative \xB7 Esc to close`})}),$jsx("box",{height:1}),rows3===null?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"loading\u2026"})}):n===0?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"Empty \u2014 no turns yet."})}):$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("box",{flexDirection:"column",children:rows3.map((m2,i)=>{let t2=tag(m2,theme);return $jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:t2.fg,children:trunc5(t2.label,13)})}),$jsx("box",{flexGrow:1,minWidth:0,height:1,overflow:"hidden",children:$jsx("text",{fg:m2.role==="tool"||m2.role==="system"?theme.textMuted:theme.text,children:body(m2).replace(/\n/g," ")})})]},i)})})})]})},openHistory=(dialog,gw)=>dialog.replace($jsx(HistoryDialog,{gw}));var import_react123=__toESM(require_react_production(),1);var InfoDialog=(props)=>{let theme=useTheme().theme,body2=props.rows.filter((r)=>r[1]!==void 0);return $jsxs("box",{flexDirection:"column",minWidth:52,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsx("strong",{children:props.title})})}),props.lines?.length?$jsx("box",{flexDirection:"column",children:props.lines.map((line4,i)=>$jsx("box",{height:1,children:$jsx("text",{fg:theme.text,children:line4})},i))}):null,$jsx("box",{flexDirection:"column",children:$jsx(KVBlock,{rows:body2})}),props.note?$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:props.note})}):null,$jsx("box",{height:1,children:$jsx("text",{fg:theme.borderSubtle,children:"Esc to close"})})]})};function openStatus(dialog,info2,sid2){let toolsets=Object.keys(info2?.tools??{}),nTools=Object.values(info2?.tools??{}).reduce((n,v2)=>n+v2.length,0),mcp=info2?.mcp_servers??[],up=mcp.filter((s)=>s.connected).length;dialog.replace($jsx(InfoDialog,{title:"Status",rows:[["Version",info2?.version||"\u2014"],["Model",info2?.model||"\u2014"],["Profile",activeProfileName()],["Home",hermesPath("")],["CWD",info2?.cwd||process.cwd()],["Session",sid2||"\u2014"],["Tools",`${nTools} in ${toolsets.length} toolset${toolsets.length===1?"":"s"}`],["Skills",String(Object.values(info2?.skills??{}).reduce((n,v2)=>n+v2.length,0))],["MCP",mcp.length?`${up}/${mcp.length} connected`:void 0]]}))}var UsageDialog=({gw})=>{let theme=useTheme().theme,[u3,setU]=import_react123.useState(null),[err,setErr]=import_react123.useState("");if(import_react123.useEffect(()=>{gw.request("session.usage").then(setU).catch((e)=>setErr(e instanceof Error?e.message:String(e)))},[gw]),err)return $jsx(InfoDialog,{title:"Usage",rows:[["Error",err,theme.error]]});if(!u3)return $jsx(InfoDialog,{title:"Usage",rows:[["","\u2026"]]});let ctx=u3.context_max?`${fmt(u3.context_used??0)} / ${fmt(u3.context_max)} (${Math.round(u3.context_percent??0)}%)`:void 0;return $jsx(InfoDialog,{title:"Usage",lines:u3.credits_lines,note:u3.cost_status==="estimated"?"cost is estimated":void 0,rows:[["Model",u3.model||"\u2014"],["API calls",String(u3.calls??0)],["Input",fmt(u3.input??0)],["Output",fmt(u3.output??0)],["Cache r/w",u3.cache_read||u3.cache_write?`${fmt(u3.cache_read??0)} / ${fmt(u3.cache_write??0)}`:void 0],["Reasoning",u3.reasoning?fmt(u3.reasoning):void 0],["Total",fmt(u3.total??0)],["Context",ctx],["Cost",u3.cost_usd!=null?cost2(u3.cost_usd):void 0,theme.accent]]})},openUsage=(dialog,gw)=>dialog.replace($jsx(UsageDialog,{gw})),ProfileDialog=()=>{let[p,setP]=import_react123.useState(void 0),active=activeProfileName();if(import_react123.useEffect(()=>{listProfiles().then((ps)=>setP(ps.find((x2)=>x2.name===active)??null)).catch(()=>setP(null))},[]),p===void 0)return $jsx(InfoDialog,{title:"Profile",rows:[["","\u2026"]]});return $jsx(InfoDialog,{title:"Profile",note:p?void 0:"profile directory not found",rows:[["Active",active],["Home",p?.path??hermesPath("")],["Model",p?.model??"\u2014"],["Provider",p?.provider??"\u2014"],["Skills",p?String(p.skill_count):void 0],["Gateway",p?.gateway_running?"running":"stopped"],["Sticky",p?.is_sticky?"yes":void 0],["Alias",p?.is_default?void 0:p?.has_alias?`~/.local/bin/${active}`:"\u2014"],[".env",p?.has_env?"present":"\u2014"]]})},openProfile=(dialog)=>dialog.replace($jsx(ProfileDialog,{}));var import_react124=__toESM(require_react_production(),1);import{spawnSync as spawnSync3}from"child_process";import{existsSync as existsSync25}from"fs";var CHAFA=["/usr/sbin/chafa","/usr/bin/chafa","/usr/local/bin/chafa","/opt/homebrew/bin/chafa"];function whichChafa(){for(let p of CHAFA)if(existsSync25(p))return p;return null}function render(path7,w2,h2){let bin=whichChafa();if(!bin)return{err:"chafa not installed (brew/apt install chafa)"};let full=path7.startsWith("~")?path7.replace(/^~/,process.env.HOME??""):path7;if(!existsSync25(full))return{err:`file not found: ${full}`};let r=spawnSync3(bin,[`--size=${w2}x${h2}`,"--format=symbols","--symbols=block","--colors=full",full],{encoding:"utf8"});if(r.status!==0)return{err:r.stderr||`chafa exit ${r.status}`};return{rows:parseChafa(r.stdout)}}var ChafaDialog=({path:path7})=>{let theme=useTheme().theme,[w2]=import_react124.useState(80),[h2]=import_react124.useState(28),result=import_react124.useMemo(()=>render(path7,w2,h2),[path7,w2,h2]);return $jsxs("box",{flexDirection:"column",minWidth:w2+4,gap:1,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.primary,children:$jsxs("strong",{children:["chafa demo \xB7 ",path7]})})}),result.err?$jsx("box",{height:1,children:$jsx("text",{fg:theme.error,children:result.err})}):$jsx("box",{flexDirection:"column",children:result.rows.map((row4,i)=>$jsx("text",{children:row4.map((c,j2)=>$jsx("span",{fg:hex(c.fg),bg:hex(c.bg),children:c.ch},j2))},i))}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.borderSubtle,children:[result.rows?`${result.rows.length} rows \xB7 ${result.rows.reduce((a,r)=>a+r.length,0)} cells \xB7 `:"","Esc to close"]})})]})};function openChafa(dialog,path7){dialog.replace($jsx(ChafaDialog,{path:path7}))}var import_react126=__toESM(require_react_production(),1);import{tmpdir as tmpdir4}from"os";import{join as join23}from"path";import{rm}from"fs/promises";async function editInEditor(renderer,seed){let cmd=process.env.VISUAL||process.env.EDITOR;if(!cmd)return;let path7=join23(tmpdir4(),`herm-${Date.now()}.md`);await Bun.write(path7,seed),renderer.suspend(),renderer.currentRenderBuffer.clear();let parts2=cmd.split(" ");await Bun.spawn([...parts2,path7],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;let text4=await Bun.file(path7).text().catch(()=>"");if(rm(path7,{force:!0}).catch(()=>{}),renderer.isDestroyed)return text4.trim()||void 0;return renderer.currentRenderBuffer.clear(),renderer.resume(),renderer.requestRender(),text4.trim()||void 0}var exports_selection={};__export(exports_selection,{yank:()=>yank,key:()=>key4,Selection:()=>exports_selection});function yank(renderer,toast){let text4=renderer.getSelection()?.getSelectedText();if(!text4)return!1;return copy(text4).then(()=>toast?.push("Copied to clipboard","info")).catch(()=>toast?.push("Clipboard write failed","err")),renderer.clearSelection(),!0}function key4(renderer,evt,toast){let sel=renderer.getSelection();if(!sel?.getSelectedText())return!1;if(evt.ctrl&&evt.name==="c")return yank(renderer,toast),!0;if(evt.name==="escape")return renderer.clearSelection(),!0;let focus=renderer.currentFocusedRenderable;if(focus&&sel.selectedRenderables.includes(focus))return!1;return renderer.clearSelection(),!1}var SGR_MOUSE_BLOB_RE=/^(?:\x1b\[|\^\[\[)?<?\d+(?:;\d+){1,2}[Mm]$/,SGR_MOUSE_RESIDUE_RE=/^\d+(?:;\d+){1,2}[Mm]$/;function isDegradedMouseInput(key5){return[key5.raw,key5.sequence,key5.name].some((v2)=>typeof v2==="string"&&isDegradedMouseBlob(v2))}function isDegradedMouseBlob(text4){if(!text4||/\s/.test(text4))return!1;return SGR_MOUSE_BLOB_RE.test(text4)||SGR_MOUSE_RESIDUE_RE.test(text4)}var DEFAULT_VOICE_KEY={mod:"ctrl",ch:"b",raw:"ctrl+b"},MOD_ALIASES={alt:"alt",ctrl:"ctrl",control:"ctrl",option:"alt",opt:"alt"};function parseVoiceRecordKey(raw2){if(typeof raw2!=="string"||!raw2.trim())return DEFAULT_VOICE_KEY;let lower=raw2.trim().toLowerCase(),parts2=lower.split("+").map((p)=>p.trim()).filter(Boolean);if(parts2.length<2)return DEFAULT_VOICE_KEY;if(parts2.length>2)return DEFAULT_VOICE_KEY;let[modRaw,chRaw]=parts2,mod=MOD_ALIASES[modRaw];if(!mod)return DEFAULT_VOICE_KEY;if(chRaw.length!==1)return DEFAULT_VOICE_KEY;if(mod==="ctrl"&&(chRaw==="c"||chRaw==="d"||chRaw==="l"))return DEFAULT_VOICE_KEY;return{mod,ch:chRaw,raw:lower}}function formatVoiceRecordKey(v2){return`${v2.mod[0].toUpperCase()+v2.mod.slice(1)}+${v2.ch.toUpperCase()}`}function isVoiceToggleKey(key5,configured2=DEFAULT_VOICE_KEY){if(key5.name.toLowerCase()!==configured2.ch)return!1;if(key5.shift)return!1;switch(configured2.mod){case"ctrl":return key5.ctrl&&!key5.meta&&!key5.super;case"alt":return key5.meta&&!key5.ctrl&&!key5.super}}function redraw(renderer){resolveRenderLib().clearTerminal(renderer.rendererPtr),renderer.currentRenderBuffer.clear(RGBA.fromValues(0,0,0,0)),renderer.requestRender()}var INTERRUPT_MS=5000,DOUBLE_TAB_MS=400,QUIT_MS=2000;function useAppKeys(o){let renderer=useRenderer(),keys=useKeys(),lastEsc=import_react126.useRef(0),lastTab=import_react126.useRef(0),lastQuit=import_react126.useRef(0),regionFor=(t2)=>t2===o.chatTab?"input":"content";import_react126.useEffect(()=>{let found=conflicts(keys.table).filter((c)=>!(c.a==="session.interrupt"&&c.b==="dialog.cancel")).filter((c)=>!(c.a==="app.exit"&&c.b==="input.clear"));if(found.length===0)return;let first=found[0];o.onNotice(`Keybinding conflict: ${print([first.chord])} \u2192 ${first.a} and ${first.b}`+(found.length>1?` (+${found.length-1} more)`:""))},[keys.table]),useKeyboard((key5)=>{let c=o.composer.current;if(isDegradedMouseInput(key5)){key5.stopPropagation();return}if(exports_selection.key(renderer,key5)){key5.stopPropagation();return}if(keys.match("input.clear",key5)&&c&&!c.isEmpty()){let v2=c.value().trim();if(v2.length>=20)c.remember(v2);c.set(""),lastQuit.current=0,key5.stopPropagation();return}if(keys.match("input.stash",key5)){o.onStash(),key5.stopPropagation();return}if(keys.match("app.exit",key5)){let now2=Date.now();if(now2-lastQuit.current<QUIT_MS)return o.onQuit();lastQuit.current=now2,o.onQuitArm(keys.print("app.exit")),key5.stopPropagation();return}if(keys.match("app.suspend",key5)){renderer.suspend(),process.kill(process.pid,"SIGTSTP"),process.once("SIGCONT",()=>renderer.resume());return}if(keys.match("app.redraw",key5)){redraw(renderer),key5.stopPropagation();return}if(keys.match("app.sidebar",key5)){o.onToggleSidebar();return}if(o.dialogOpen())return;if(o.voiceRecordKey&&o.onVoiceRecord&&isVoiceToggleKey(key5,o.voiceRecordKey)){o.onVoiceRecord(),key5.stopPropagation();return}if(c?.mode()==="shell"){if(key5.name==="escape"){c.setMode("normal"),key5.stopPropagation();return}if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c.caret()===0){c.setMode("normal"),key5.stopPropagation();return}}if(keys.match("session.steer",key5)){o.onSteer(),key5.stopPropagation();return}if(keys.match("queue.flush",key5)&&o.streaming&&o.queued>0){o.onFlushQueue(),key5.stopPropagation();return}if(o.onPromptKey&&!keys.leader&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(o.onPromptKey(key5)){key5.stopPropagation();return}}if(keys.match("editor.open",key5)&&!o.streaming){let seed=c?.value()??"";editInEditor(renderer,seed).then((out)=>{if(out===void 0){if(!process.env.VISUAL&&!process.env.EDITOR)o.onNotice("Set $EDITOR or $VISUAL to use the external editor");return}c?.set(out),o.setFocusRegion("input")});return}if(keys.match("tab.prev",key5)){o.setTab((t2)=>{let n=Math.max(0,t2-1);return o.setFocusRegion(regionFor(n)),n});return}if(keys.match("tab.next",key5)){o.setTab((t2)=>{let n=Math.min(o.tabMax,t2+1);return o.setFocusRegion(regionFor(n)),n});return}if(o.subCount>0&&key5.shift&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name==="left"){o.cycleSub(-1),key5.stopPropagation();return}if(key5.name==="right"){o.cycleSub(1),key5.stopPropagation();return}}if(keys.leader&&!key5.ctrl&&!key5.meta&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(key5.meta&&!key5.ctrl&&!key5.shift&&key5.eventType!=="release"){let n={"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"0":9,"-":10}[key5.name];if(n!==void 0&&n<=o.tabMax){o.setTab(()=>{return o.setFocusRegion(regionFor(n)),n}),key5.stopPropagation();return}}if(c?.popOpen()){if(key5.name==="escape")return c.popCancel();if(key5.name==="up"){c.popNav(-1),key5.stopPropagation();return}if(key5.name==="down"){c.popNav(1),key5.stopPropagation();return}if(key5.name==="tab")return c.popAccept();return}if(keys.match("focus.cycle",key5)&&!o.streaming){if(o.tab===o.chatTab){o.setFocusRegion((r)=>r==="input"?"content":"input");return}if(o.focusRegion==="input"){o.setFocusRegion("content");return}let now2=Date.now();if(now2-lastTab.current<DOUBLE_TAB_MS)o.setFocusRegion("input"),lastTab.current=0,key5.stopPropagation();else lastTab.current=now2;return}if(keys.match("session.interrupt",key5)){if(!o.streaming&&o.onEscape?.())return;if(o.streaming){let now2=Date.now();if(now2-lastEsc.current<INTERRUPT_MS){o.onInterrupt(),lastEsc.current=0;return}lastEsc.current=now2,o.onInterruptNotice();return}if(o.tab===o.chatTab&&o.focusRegion==="content")o.setFocusRegion("input");return}if(keys.match("reply.copy",key5))return o.onCopyLast();if(keys.match("clipboard.attach",key5)){o.onAttachClipboard(),key5.stopPropagation();return}if(o.focusRegion==="input"&&!o.streaming){if((key5.name==="!"||key5.name==="1"&&key5.shift)&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"&&c&&c.mode()==="normal"&&!c.popOpen()&&c.caret()===0){c.setMode("shell"),key5.stopPropagation();return}if(key5.name==="up")return void c?.historyUp();if(key5.name==="down")return void c?.historyDown();if(key5.name==="backspace"&&!key5.ctrl&&!key5.meta&&c?.isEmpty()&&o.onDetachLast()){key5.stopPropagation();return}}if(o.tab===o.chatTab&&o.focusRegion==="content"&&!o.streaming&&!key5.ctrl&&!key5.meta&&key5.eventType!=="release"){if(key5.name.length===1&&key5.name!==" "){let ch=key5.shift&&/[a-z]/.test(key5.name)?key5.name.toUpperCase():key5.name;o.setFocusRegion("input"),c?.insert(ch),key5.stopPropagation()}}})}import{writeSync}from"fs";var done=!1;function quit(renderer,sid2,title,gw){if(done)process.exit(0);done=!0;try{gw?.kill()}catch{}if(renderer.destroy(),process.stdout.isTTY){let banner=sid2?`
|
|
4179
4181
|
continue herm --resume ${sid2}${title?` \u2014 ${title.slice(0,60)}`:""}
|
|
4180
4182
|
|
|
4181
4183
|
`:`
|
|
4182
4184
|
bye
|
|
4183
4185
|
|
|
4184
|
-
`;writeSync(1,banner)}process.exit(0)}var exports_stash={};__export(exports_stash,{push:()=>push2,pop:()=>pop2,drop:()=>drop,all:()=>all,Stash:()=>exports_stash});import{join as join24}from"path";import{existsSync as
|
|
4185
|
-
`).filter(Boolean).map((l)=>JSON.parse(l)).slice(-MAX)}function save3(list3){
|
|
4186
|
+
`;writeSync(1,banner)}process.exit(0)}var exports_stash={};__export(exports_stash,{push:()=>push2,pop:()=>pop2,drop:()=>drop,all:()=>all,Stash:()=>exports_stash});import{join as join24}from"path";import{existsSync as existsSync26,readFileSync as readFileSync18,writeFileSync as writeFileSync8,mkdirSync as mkdirSync6}from"fs";var MAX=50,file2=()=>join24(configDir(),"stash.jsonl");function load5(){if(!existsSync26(file2()))return[];return readFileSync18(file2(),"utf-8").split(`
|
|
4187
|
+
`).filter(Boolean).map((l)=>JSON.parse(l)).slice(-MAX)}function save3(list3){mkdirSync6(configDir(),{recursive:!0}),writeFileSync8(file2(),list3.map((e)=>JSON.stringify(e)).join(`
|
|
4186
4188
|
`)+`
|
|
4187
|
-
`,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let
|
|
4188
|
-
`)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,
|
|
4189
|
+
`,"utf-8")}function push2(text4){let list3=load5(),at=Math.max(Date.now(),(list3[list3.length-1]?.at??0)+1);if(list3.push({text:text4,at}),list3.length>MAX)list3.shift();return save3(list3),list3.length}function pop2(){let list3=load5(),e=list3.pop();if(!e)return null;return save3(list3),e}function all(){return load5().reverse()}function drop(at){save3(load5().filter((e)=>e.at!==at))}var import_react127=__toESM(require_react_production(),1);var ctx=import_react127.createContext(null),BackgroundProvider=({children:children2})=>{let[set2,setSet]=import_react127.useState(()=>new Set),register2=import_react127.useCallback((id)=>{if(!id)return;setSet((prev)=>prev.has(id)?prev:new Set(prev).add(id))},[]),unregister=import_react127.useCallback((id)=>{setSet((prev)=>{if(!prev.has(id))return prev;let next2=new Set(prev);return next2.delete(id),next2})},[]),ids3=import_react127.useMemo(()=>Array.from(set2),[set2]),value=import_react127.useMemo(()=>({count:ids3.length,ids:ids3,register:register2,unregister}),[ids3,register2,unregister]);return $jsx(ctx.Provider,{value,children:children2})},useBackground=makeUse(ctx,"useBackground");var initialTurn={messages:[],streaming:!1,hasContent:!1,toolActive:!1};function turnReducer(state2,a){switch(a.kind){case"reset":return initialTurn;case"load":return{...initialTurn,messages:a.messages};case"load.live":return{...initialTurn,messages:a.messages,streaming:a.streaming,hasContent:a.streaming&&Boolean(joinText(a.messages.at(-1)?.parts??[]))};case"push":return{...state2,messages:[...state2.messages,a.message]};case"user":return{...state2,messages:[...state2.messages,userMessage(a.text)]};case"system":return{...state2,messages:[...state2.messages,systemMessage(sanitize(a.text))]};case"message.start":return{...state2,streaming:!0,hasContent:!1,toolActive:!1};case"message.delta":{let chunk=sanitize(a.chunk);if(!chunk)return state2;return{...state2,hasContent:!0,toolActive:!1,messages:appendText(state2.messages,chunk)}}case"message.complete":return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:finalize(state2.messages,a.text!=null?sanitize(a.text):void 0,a.usage)};case"tool.start":{let preview2=sanitize(a.preview),args=sanitize(a.args),raw2=args||preview2,json=raw2&&/^\s*\{/.test(raw2),part={type:"tool",id:a.id,name:a.name,args:json?raw2:"",status:"running",startedAt:Date.now(),preview:preview2||void 0,verboseArgs:args||void 0};return{...state2,toolActive:!0,hasContent:!1,messages:appendPart(state2.messages,part,!0)}}case"tool.progress":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:sanitize(a.preview)||p.preview}))};case"tool.generating":return{...state2,messages:updateRunningTool(state2.messages,a.name,(p)=>({...p,preview:p.preview??"generating\u2026"}))};case"tool.complete":{let summary2=sanitize(a.summary),error=sanitize(a.error),diff=sanitize(a.inline_diff),result=sanitize(a.result);return{...state2,toolActive:!1,messages:updateToolById(state2.messages,a.id,(p)=>({...p,status:a.error?"error":"done",duration:a.duration??(p.startedAt?Date.now()-p.startedAt:void 0),preview:summary2||diff||p.preview,result:error||summary2||void 0,verboseResult:result||void 0,diff:diff||void 0}))}}case"thinking":return{...state2,messages:upsertThinking(state2.messages,sanitize(a.text),a.final,a.verbose)};case"subagent":return{...state2,messages:renderSubagent(state2.messages,a.event,a.payload)};case"prompt":{let part={type:"prompt",id:a.id,variant:a.req.variant,req:a.req};return{...state2,messages:appendPart(state2.messages,part,!0)}}case"prompt.answered":return{...state2,messages:updatePrompt(state2.messages,a.id,(p)=>({...p,answered:{label:a.label,ok:a.ok,at:Date.now()}}))};case"error":{let msg=systemMessage(`Error: ${sanitize(a.text)}`);if(a.fatal===!1)return{...state2,messages:[...state2.messages,msg]};return{...state2,streaming:!1,hasContent:!1,toolActive:!1,messages:[...state2.messages,msg]}}case"interrupt.notice":{let clean4=sanitize(a.text),last3=state2.messages[state2.messages.length-1];if(last3?.role==="system"&&last3.parts[0]?.type==="text"&&last3.parts[0].content.includes(clean4))return state2;return{...state2,messages:[...state2.messages,systemMessage(clean4)]}}}}function userMessage(text4){return{id:mid(),role:"user",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function systemMessage(text4){return{id:mid(),role:"system",parts:[{type:"text",content:text4,streaming:!1}],timestamp:Date.now()/1000}}function flatten3(text4){if(typeof text4==="string")return text4;if(!Array.isArray(text4))return"";let out=[];for(let p of text4)if(p&&typeof p==="object"&&"type"in p&&p.type==="text"&&"text"in p&&typeof p.text==="string")out.push(p.text);return out.join(`
|
|
4190
|
+
`)}function transcriptToMessages(rows3){return rows3.filter((r)=>r.role==="user"||r.role==="assistant").map((r)=>({role:r.role,content:sanitize(flatten3(r.text))})).filter((r)=>r.content).map((r)=>({id:mid(),role:r.role,parts:[{type:"text",content:r.content,streaming:!1}],timestamp:Date.now()/1000}))}function assistant(parts2){return{id:mid(),role:"assistant",parts:parts2,timestamp:Date.now()/1000}}function withLastAssistant(messages,fn,otherwise){let last3=messages[messages.length-1];if(last3?.role==="assistant")return[...messages.slice(0,-1),fn(last3)];return[...messages,otherwise()]}function seal(parts2){let last3=parts2[parts2.length-1];if(last3?.type==="text"&&last3.streaming)return[...parts2.slice(0,-1),{...last3,streaming:!1}];return parts2}function appendText(messages,chunk){return withLastAssistant(messages,(m2)=>{let last3=m2.parts[m2.parts.length-1];if(last3?.type==="text"&&last3.streaming){let part={...last3,content:last3.content+chunk};return{...m2,parts:[...m2.parts.slice(0,-1),part]}}return{...m2,parts:[...m2.parts,{type:"text",key:pid(),content:chunk,streaming:!0}]}},()=>assistant([{type:"text",key:pid(),content:chunk,streaming:!0}]))}function appendPart(messages,part,close){return withLastAssistant(messages,(m2)=>({...m2,parts:[...close?seal(m2.parts):m2.parts,part]}),()=>assistant([part]))}function finalize(messages,final,usage){let last3=messages[messages.length-1];if(last3?.role==="assistant"){let tail=last3.parts[last3.parts.length-1],dup=final&&last3.parts.some((p)=>p.type==="text"&&sameText(p.content,final)),text4=tail?.type==="text"&&final&&sameText(tail.content,final)?tail.content:final,parts2=tail?.type==="text"&&tail.streaming?[...last3.parts.slice(0,-1),{...tail,content:text4||tail.content,streaming:!1}]:final&&!dup&&!sameText(joinText(last3.parts),final)?[...last3.parts,{type:"text",content:final,streaming:!1}]:seal(last3.parts);return[...messages.slice(0,-1),{...last3,parts:parts2,usage}]}if(!final)return messages;return[...messages,{...assistant([{type:"text",content:final,streaming:!1}]),usage}]}function joinText(parts2){return parts2.filter((p)=>p.type==="text").map((p)=>p.content).join("")}function sameText(a,b2){return a.trim()===b2.trim()}function updateRunningTool(messages,name,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;for(let i=last3.parts.length-1;i>=0;i--){let p=last3.parts[i];if(p.type!=="tool"||p.status!=="running")continue;if(name&&p.name!==name)continue;let parts2=[...last3.parts];return parts2[i]=fn(p),[...messages.slice(0,-1),{...last3,parts:parts2}]}return messages}function updateToolById(messages,id,fn){let last3=messages[messages.length-1];if(!last3||last3.role!=="assistant")return messages;let parts2=last3.parts.map((p)=>p.type==="tool"&&p.id===id?fn(p):p);return[...messages.slice(0,-1),{...last3,parts:parts2}]}function updatePrompt(messages,id,fn){return messages.map((m2)=>{if(m2.role!=="assistant")return m2;if(!m2.parts.some((p)=>p.type==="prompt"&&p.id===id))return m2;return{...m2,parts:m2.parts.map((p)=>p.type==="prompt"&&p.id===id?fn(p):p)}})}function upsertThinking(messages,text4,final,verbose2){return withLastAssistant(messages,(m2)=>{let idx=m2.parts.findIndex((p)=>p.type==="thinking");if(idx>=0){let prev=m2.parts[idx],content=final?prev.content.trim()||text4:prev.content+text4,parts2=[...m2.parts];return parts2[idx]={...prev,content,streaming:!final,verbose:prev.verbose||verbose2||void 0},{...m2,parts:parts2}}return{...m2,parts:[{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2},...m2.parts]}},()=>assistant([{type:"thinking",key:pid(),content:text4,streaming:!final,verbose:verbose2}]))}function renderSubagent(messages,event,p){let id=p.subagent_id?`sub-${p.subagent_id}`:`sub-${p.task_index}`;if(event==="start"){let goal=sanitize(p.goal),part={type:"tool",id,name:"delegate_task",args:"",status:"running",startedAt:Date.now(),preview:goal||void 0,goal:goal||void 0,depth:p.depth??0,trail:[]};return appendPart(messages,part,!0)}if(event==="tool"&&p.tool_name){let tname=sanitize(p.tool_name),tprev=sanitize(p.tool_preview);return updateToolById(messages,id,(t2)=>({...t2,trail:[...t2.trail??[],{name:tname,preview:tprev||void 0}],preview:tprev?`${tname}: ${tprev}`:tname}))}if(event==="complete"){let tokens3=(p.input_tokens??0)+(p.output_tokens??0),extra=tokens3?` \xB7 ${(tokens3/1000).toFixed(1)}k tok`:"",summary2=sanitize(p.summary);return updateToolById(messages,id,(t2)=>({...t2,status:p.status==="failed"||p.status==="error"||p.status==="timeout"||p.status==="interrupted"?"error":"done",duration:p.duration_seconds?p.duration_seconds*1000:t2.startedAt?Date.now()-t2.startedAt:void 0,result:summary2?summary2+extra:void 0,preview:t2.goal??t2.preview}))}return updateToolById(messages,id,(t2)=>({...t2,preview:sanitize(p.text)||t2.preview}))}function useSlash(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),themeCtx=useTheme(),cmd=useCommand(),renderer=useRenderer(),cfg=useHome("config"),bg2=useBackground(),ctx2=import_react128.useRef(c);ctx2.current=c;let gate=import_react128.useRef(cfg);gate.current=cfg;let destructive=import_react128.useCallback((arg,opts,action)=>{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",bypass=!(gate.current?.approvals?.destructive_slash_confirm??!0)||process.env.HERMES_TUI_NO_CONFIRM==="1",persist2=a==="always",fire=()=>{if(persist2)Promise.resolve().then(() => (init_lane(),exports_lane)).then(({writeConfig:writeConfig2})=>writeConfig2(gw,[{key:"approvals.destructive_slash_confirm",to:!1}]).then((r)=>{if(r.failed.length){toast.show({variant:"warning",message:`couldn't persist: ${r.failed[0].err}`});return}home2.invalidate("config"),toast.show({variant:"success",message:`${opts.yes} \xB7 future runs silent`})}).catch((e)=>toast.show({variant:"error",message:e.message})));action()};if(skip||bypass)return fire();openConfirm(dialog,{title:opts.title,body:opts.body,yes:opts.yes,danger:!0}).then((ok)=>{if(ok)fire()})},[gw,dialog,toast]),pickEikon=import_react128.useCallback(()=>openEikonPicker(dialog,(n)=>set("eikon",n)),[dialog]),applyTitle=import_react128.useCallback((t2)=>{gw.request("session.title",{title:t2}).then((r)=>{ctx2.current.setTitle(r.title),ctx2.current.dispatch({kind:"system",text:`Title: ${r.title}`})}).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),runCompress=import_react128.useCallback(async()=>{toast.show({variant:"info",message:"Compressing session\u2026"});let r=await ctx2.current.session.compress();if(!r)return;if(r.info)ctx2.current.setInfo(r.info);if(ctx2.current.setUsage((u3)=>{let base2=r.usage??u3,max=r.usage?.context_max??u3?.context_max;if(typeof r.after_tokens!=="number"||typeof max!=="number")return base2;return{...base2??{input:0,output:0,total:0},context_used:r.after_tokens,context_max:max}}),!r.summary)return;let s=r.summary;if(s.noop){toast.show({variant:"info",message:s.headline??`No changes \xB7 ~${r.before_tokens??0} tokens`});return}let lines3=[s.headline,s.token_line,s.note].filter(Boolean).join(`
|
|
4189
4191
|
`);if(lines3)ctx2.current.dispatch({kind:"system",text:lines3});toast.show({variant:"success",message:s.headline??`Compressed ${r.before_messages??0}\u2192${r.after_messages??0} messages`})},[toast]),branch2=import_react128.useCallback((name)=>{let x2=ctx2.current;x2.session.branch(name?.trim()||void 0).then((id)=>id?void x2.activateSession(id):toast.show({variant:"error",message:"branch failed"}))},[toast]),run=import_react128.useCallback((c2,arg="")=>{let x2=ctx2.current;if(c2.target==="local")switch(c2.name){case"clear":destructive(arg,{title:"Clear session?",body:"Discards the in-memory transcript. Your session on disk is unchanged; reload to restore.",yes:"clear"},()=>x2.dispatch({kind:"reset"}));return;case"new":destructive(arg,{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{x2.newSession()});return;case"theme":{let mode=arg.trim().toLowerCase();if(!mode){openThemePicker(dialog,themeCtx);return}if(mode==="light"||mode==="dark"){themeCtx.setMode(mode),x2.dispatch({kind:"system",text:`theme mode \u2192 ${mode}`});return}toast.show({variant:"error",message:"usage: /theme [light|dark]"});return}case"help":dialog.replace($jsx(HelpDialog,{}));return;case"keys":openKeys(dialog);return;case"logs":openLogs(dialog);return;case"title":if(arg){applyTitle(arg);return}openTextPrompt(dialog,{title:"Session Title",initial:x2.title}).then((v2)=>{if(v2)applyTitle(v2)});return;case"rollback":openRollback(dialog,gw,toast);return;case"history":openHistory(dialog,gw);return;case"status":openStatus(dialog,x2.info,x2.sid);return;case"usage":openUsage(dialog,gw);return;case"profile":openProfile(dialog);return;case"chafa":if(!arg.trim()){toast.show({variant:"info",message:"usage: /chafa <path>"});return}openChafa(dialog,arg.trim());return;case"splash":x2.summoned.current=!0,x2.setSplash(!0);return;case"skin":{let name=arg.trim();if(!name){x2.dispatch({kind:"system",text:`skin: ${x2.skin.skin?.name??"\u2014"}
|
|
4190
|
-
${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikon",void 0),x2.dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){x2.switchSession(arg);return}x2.goTo(TAB_SLASH.sessions.tab,TAB_SLASH.sessions.sub);return;case"branch":branch2(arg);return;case"compress":runCompress();return;case"undo":destructive(arg,{title:"Undo last turn?",body:"Pops the last user + assistant pair from the transcript. /redo in this session to restore.",yes:"undo"},()=>{let msgs=x2.turnRef.current.messages,at=msgs.map((m2)=>m2.role).lastIndexOf("user");if(at>=0)x2.undone.current.push(msgs.slice(at));x2.session.undo().then(()=>gw.request("session.history").then((r)=>x2.dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}))});return;case"redo":{let head=x2.undone.current.pop()?.find((m2)=>m2.role==="user");if(!head){toast.show({variant:"info",message:"nothing to redo"});return}x2.sendRef.current(text(head));return}case"retry":{let last3=[...x2.turnRef.current.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}x2.rewind(last3).then(()=>x2.sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});x2.dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"yolo":gw.request("config.set",{key:"yolo"}).then((r)=>{if(r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);else x2.setInfo({...x2.info??{},yolo:!x2.info?.yolo});if(toast.show({variant:"success",message:`yolo ${r.value??"toggled"}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,x2.sid,x2.title,gw);return;case"queue":if(!arg){x2.dispatch({kind:"system",text:`${x2.queueRef.current.length} queued`});return}x2.setQueue((q5)=>[...q5,arg]);return;case"stash":{let comp=x2.composer.current;if(arg==="pop"){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});comp?.set(e.text),x2.setFocusRegion("input");return}if(arg==="list"){let list3=exports_stash.all();if(list3.length===0)return toast.show({variant:"info",message:"stash empty"});dialog.replace($jsx(DialogSelect,{title:"Stashed prompts",filterable:list3.length>6,options:list3.map((e)=>({title:trunc5(e.text.replace(/\n/g," \u23CE "),50),value:String(e.at),hint:ago(e.at)})),onSelect:(o)=>{let e=list3.find((s)=>String(s.at)===o.value);if(e)exports_stash.drop(e.at),comp?.set(e.text),x2.setFocusRegion("input");dialog.clear()}}));return}let text4=arg||comp?.value().trim()||"";if(!text4)return toast.show({variant:"info",message:"nothing to stash \u2014 /stash list"});let n=exports_stash.push(text4);if(!arg)comp?.set("");toast.show({variant:"info",message:`stashed (${n}) \u2014 /stash pop to restore`});return}case"copy":{let all2=x2.turnRef.current.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all2.length):all2.length,m2=all2[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":x2.attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?x2.setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>{if(r.task_id)bg2.register(r.task_id);toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":x2.voiceToggle((arg||"status").toLowerCase(),x2.sid).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"browser":{let parts2=arg.trim().split(/\s+/),sub2=parts2[0]?.toLowerCase()||"connect",url2=parts2[1];if(!["connect","disconnect","status"].includes(sub2)){toast.show({variant:"error",message:"usage: /browser [connect|disconnect|status] [url]"});return}let payload={action:sub2};if(sub2==="connect"&&url2)payload.url=url2;gw.request("browser.manage",payload).then((r)=>{for(let m2 of r.messages??[])x2.dispatch({kind:"system",text:m2});if(r.connected)x2.dispatch({kind:"system",text:`Browser connected${r.url?` \u2192 ${r.url}`:""}`});else if(sub2==="disconnect")x2.dispatch({kind:"system",text:"Browser disconnected"});else if(sub2==="status")x2.dispatch({kind:"system",text:r.url??"No browser connected"})}).catch((e)=>toast.show({variant:"error",message:`browser: ${e.message}`}));return}case"compact":case"setup":x2.dispatch({kind:"system",text:`/${c2.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text4)=>gw.request("session.steer",{text:text4}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text4)=>{if(text4)fire(text4)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{x2.dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c2.target!=="gateway"||!x2.capabilities.canDispatchGatewayCommand)return;let jump=TAB_SLASH[c2.name];if(jump!==void 0&&!arg){x2.goTo(jump.tab,jump.sub);return}let full=`/${c2.name}${arg?" "+arg:""}`;if(x2.turnRef.current.streaming){x2.setQueue((q5)=>[...q5,full]);return}x2.dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)x2.dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)x2.dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c2.name,arg}).then((d2)=>{if(d2.notice)x2.dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return x2.dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void x2.sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")x2.dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c2.name}`});return void x2.sendRef.current(d2.message)}x2.dispatch({kind:"system",text:`/${c2.name}: unknown`})}).catch((e)=>x2.dispatch({kind:"system",text:`error: ${e.message}`}))})},[gw,dialog,toast,themeCtx,renderer,destructive,applyTitle,runCompress,branch2]);return import_react128.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,ctx2.current.info,ctx2.current.sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>destructive("",{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{ctx2.current.newSession()})},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>run({name:"undo",target:"local"})},{title:"Redo",value:"redo",action:"session.redo",category:"Session",onSelect:()=>run({name:"redo",target:"local"})},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>branch2()}]),[cmd,dialog,themeCtx,gw,toast,destructive,pickEikon,runCompress,branch2,run]),run}var import_react132=__toESM(require_react_production(),1);var import_react130=__toESM(require_react_production(),1);function openAlert(dialog,title,body2){dialog.replace($jsx(Alert,{title,body:body2,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied,setCopied]=import_react130.useState(!1),doCopy=()=>{copy(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key5)=>{if(keys.match("dialog.cancel",key5)||keys.match("dialog.accept",key5))props.onClose();if(keys.match("dialog.copy",key5))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:$jsx("u",{children:copied?"copied":"copy"})})})]})]})};init_perf();function variant(level2){switch(level2){case"error":return"error";case"warning":case"warn":return"warning";case"success":return"success";default:return"info"}}function duration2(p){if(p.kind==="sticky")return null;if(typeof p.ttl_ms==="number")return p.ttl_ms;if(typeof p.duration_ms==="number")return p.duration_ms;return}function showNotification(toast,p){let text4=String(p?.text??"").trim();if(!text4)return;toast.show({key:p?.key,variant:variant(p?.level),message:text4,duration:duration2(p??{text:text4})})}function clearNotification(toast,p){let key5=String(p?.key??"").trim();if(!key5)return;toast.clear(key5)}function count3(o){return o?Object.values(o).reduce((n,v2)=>n+v2.length,0):0}function formatProcessNotification(text4){let body2=text4.replace(/^\[IMPORTANT: /,"").replace(/\]$/,""),done2=body2.match(/^Background process (\S+) completed \(exit code (\S+)\)\.\nCommand: (.+?)(?:\n|$)/);if(done2)return`${done2[1]} exited ${done2[2]} \xB7 ${done2[3]}`;let hit2=body2.match(/^Background process (\S+) matched watch pattern "([^"]+)"\.\nCommand: (.+?)(?:\n|$)/);if(hit2)return`${hit2[1]} matched "${hit2[2]}" \xB7 ${hit2[3]}`;return body2.slice(0,100)}function mapEvent(ev,side){switch(ev.type){case"gateway.ready":if(side.onReady?.(),ev.payload?.skin)side.onSkin?.(ev.payload.skin);return null;case"session.info":{let si=ev.payload;side.onSessionInfo?.(si);let label2=si.model?`Connected \u2014 ${si.model} \xB7 ${count3(si.tools)} tools \xB7 ${count3(si.skills)} skills`:"Connected to Hermes";if(si.credential_warning)side.onStatus?.(si.credential_warning);return{kind:"system",text:label2}}case"message.start":return count("stream:start"),mem("stream-start"),{kind:"message.start"};case"message.delta":{let chunk2=ev.payload?.text??"";if(!chunk2)return null;return count("stream:chunk"),{kind:"message.delta",chunk:chunk2}}case"message.complete":{count("stream:done"),mem("stream-done");let p=ev.payload;if(p?.usage)side.onUsage?.(p.usage);if(side.onTurnComplete?.(),p?.status==="error")return{kind:"error",text:p.text||"request failed \u2014 see messages above"};if(p?.status==="interrupted")return{kind:"message.complete",text:(p.text||"")+`
|
|
4192
|
+
${SKINS.join(" ")}`});return}if(!SKINS.includes(name)){toast.show({variant:"error",message:`unknown skin: ${name}`});return}gw.request("config.set",{key:"skin",value:name}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});if(themeCtx.has(name))themeCtx.set(name);set("eikon",void 0),x2.dispatch({kind:"system",text:`skin \u2192 ${name}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return}case"resume":if(arg){x2.switchSession(arg);return}x2.goTo(TAB_SLASH.sessions.tab,TAB_SLASH.sessions.sub);return;case"branch":branch2(arg);return;case"compress":runCompress();return;case"undo":destructive(arg,{title:"Undo last turn?",body:"Pops the last user + assistant pair from the transcript. /redo in this session to restore.",yes:"undo"},()=>{let msgs=x2.turnRef.current.messages,at=msgs.map((m2)=>m2.role).lastIndexOf("user");if(at>=0)x2.undone.current.push(msgs.slice(at));x2.session.undo().then(()=>gw.request("session.history").then((r)=>x2.dispatch({kind:"load",messages:transcriptToMessages(r.messages??[])})).catch(()=>{}))});return;case"redo":{let head=x2.undone.current.pop()?.find((m2)=>m2.role==="user");if(!head){toast.show({variant:"info",message:"nothing to redo"});return}x2.sendRef.current(text(head));return}case"retry":{let last3=[...x2.turnRef.current.messages].reverse().find((m2)=>m2.role==="user");if(!last3){toast.show({variant:"info",message:"nothing to retry"});return}x2.rewind(last3).then(()=>x2.sendRef.current(text(last3)));return}case"model":if(!arg){openModelPicker(dialog,gw);return}gw.request("config.set",{key:"model",value:arg}).then((r)=>{if(r.warning)toast.show({variant:"warning",message:r.warning});x2.dispatch({kind:"system",text:`model \u2192 ${r.value??arg}`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"yolo":gw.request("config.set",{key:"yolo"}).then((r)=>{if(r.info)x2.setInfo(r.info),x2.setUsage(r.info.usage);else x2.setInfo({...x2.info??{},yolo:!x2.info?.yolo});if(toast.show({variant:"success",message:`yolo ${r.value??"toggled"}`}),r.warning)toast.show({variant:"warning",message:r.warning})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"quit":quit(renderer,x2.sid,x2.title,gw);return;case"queue":if(!arg){x2.dispatch({kind:"system",text:`${x2.queueRef.current.length} queued`});return}x2.setQueue((q5)=>[...q5,arg]);return;case"stash":{let comp=x2.composer.current;if(arg==="pop"){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});comp?.set(e.text),x2.setFocusRegion("input");return}if(arg==="list"){let list3=exports_stash.all();if(list3.length===0)return toast.show({variant:"info",message:"stash empty"});dialog.replace($jsx(DialogSelect,{title:"Stashed prompts",filterable:list3.length>6,options:list3.map((e)=>({title:trunc5(e.text.replace(/\n/g," \u23CE "),50),value:String(e.at),hint:ago(e.at)})),onSelect:(o)=>{let e=list3.find((s)=>String(s.at)===o.value);if(e)exports_stash.drop(e.at),comp?.set(e.text),x2.setFocusRegion("input");dialog.clear()}}));return}let text4=arg||comp?.value().trim()||"";if(!text4)return toast.show({variant:"info",message:"nothing to stash \u2014 /stash list"});let n=exports_stash.push(text4);if(!arg)comp?.set("");toast.show({variant:"info",message:`stashed (${n}) \u2014 /stash pop to restore`});return}case"copy":{let all2=x2.turnRef.current.messages.filter((m3)=>m3.role==="assistant"),n=arg?Math.min(Math.max(1,parseInt(arg,10)||0),all2.length):all2.length,m2=all2[n-1];if(!m2){toast.show({variant:"info",message:"nothing to copy"});return}let body2=text(m2);copy(body2),toast.show({variant:"success",message:`copied ${body2.length} chars`});return}case"paste":x2.attachClipboard();return;case"image":if(!arg){toast.show({variant:"info",message:"usage: /image <path>"});return}gw.request("image.attach",{path:arg}).then((r)=>r.attached?x2.setAttachments((a)=>[...a,r]):toast.show({variant:"warning",message:r.message??"attach failed"})).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"background":if(!arg){toast.show({variant:"info",message:"usage: /background <prompt>"});return}gw.request("prompt.background",{text:arg}).then((r)=>{if(r.task_id)bg2.register(r.task_id);toast.show(r.task_id?{variant:"success",message:`background ${r.task_id} started`}:{variant:"error",message:"background start failed"})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"voice":x2.voiceToggle((arg||"status").toLowerCase(),x2.sid).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"mouse":{let want=arg==="on"?!0:arg==="off"?!1:!renderer.useMouse;renderer.useMouse=want,set("mouse",want),toast.show({variant:"info",message:`mouse ${want?"on":"off"}`});return}case"redraw":redraw(renderer);return;case"browser":{let parts2=arg.trim().split(/\s+/),sub2=parts2[0]?.toLowerCase()||"connect",url2=parts2[1];if(!["connect","disconnect","status"].includes(sub2)){toast.show({variant:"error",message:"usage: /browser [connect|disconnect|status] [url]"});return}let payload={action:sub2};if(sub2==="connect"&&url2)payload.url=url2;gw.request("browser.manage",payload).then((r)=>{for(let m2 of r.messages??[])x2.dispatch({kind:"system",text:m2});if(r.connected)x2.dispatch({kind:"system",text:`Browser connected${r.url?` \u2192 ${r.url}`:""}`});else if(sub2==="disconnect")x2.dispatch({kind:"system",text:"Browser disconnected"});else if(sub2==="status")x2.dispatch({kind:"system",text:r.url??"No browser connected"})}).catch((e)=>toast.show({variant:"error",message:`browser: ${e.message}`}));return}case"compact":case"setup":x2.dispatch({kind:"system",text:`/${c2.name} is an Ink-TUI command and has no effect in herm`});return;case"steer":{let fire=(text4)=>gw.request("session.steer",{text:text4}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(arg){fire(arg);return}openTextPrompt(dialog,{title:"Steer",label:"Note to inject on next tool result"}).then((text4)=>{if(text4)fire(text4)});return}case"reload-mcp":{let a=arg.trim().toLowerCase(),skip=a==="now"||a==="once"||a==="approve"||a==="yes"||a==="always",fire=(always)=>gw.request("reload.mcp",{confirm:!0,always}).then((r)=>r.status==="confirm_required"?toast.show({variant:"warning",message:r.message??"reload requires confirmation"}):toast.show({variant:"success",message:always?"MCP servers reloaded \xB7 future /reload-mcp runs silently":"MCP servers reloaded"})).catch((e)=>toast.show({variant:"error",message:e.message}));if(skip){fire(a==="always");return}openConfirm(dialog,{title:"Reload MCP servers?",body:"Rebuilds the MCP tool set. Invalidates the prompt cache, so the next message re-sends full input tokens.",yes:"reload",danger:!0}).then((ok)=>{if(ok)fire(!1)});return}case"reload":gw.request("reload.env",{}).then((r)=>{let n=Number(r.updated??0);toast.show({variant:"success",message:`Reloaded .env (${n} var${n===1?"":"s"} updated) \xB7 /new to apply`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"reload-skills":gw.request("skills.reload",{}).then((r)=>{x2.dispatch({kind:"system",text:r.output});let n=Number(r.result?.total??0);toast.show({variant:"success",message:`Skills reloaded (${n} available)`})}).catch((e)=>toast.show({variant:"error",message:e.message}));return;case"save":gw.request("session.save").then((r)=>toast.show({variant:"success",message:`Saved \u2192 ${r.file}`})).catch((e)=>toast.show({variant:"error",message:e.message}));return}if(c2.target!=="gateway"||!x2.capabilities.canDispatchGatewayCommand)return;let jump=TAB_SLASH[c2.name];if(jump!==void 0&&!arg){x2.goTo(jump.tab,jump.sub);return}let full=`/${c2.name}${arg?" "+arg:""}`;if(x2.turnRef.current.streaming){x2.setQueue((q5)=>[...q5,full]);return}x2.dispatch({kind:"user",text:full}),gw.request("slash.exec",{command:full}).then((res)=>{if(res?.warning)x2.dispatch({kind:"system",text:`\u26A0 ${res.warning}`});if(res?.output)x2.dispatch({kind:"system",text:res.output})}).catch(()=>{gw.request("command.dispatch",{name:c2.name,arg}).then((d2)=>{if(d2.notice)x2.dispatch({kind:"system",text:d2.notice});if(d2.type==="exec"||d2.type==="plugin")return x2.dispatch({kind:"system",text:d2.output||"(no output)"});if(d2.type==="alias"&&d2.target)return void x2.sendRef.current(`/${d2.target}${arg?" "+arg:""}`);if((d2.type==="skill"||d2.type==="send")&&d2.message){if(d2.type==="skill")x2.dispatch({kind:"system",text:`\u26A1 loading skill: ${d2.name??c2.name}`});return void x2.sendRef.current(d2.message)}x2.dispatch({kind:"system",text:`/${c2.name}: unknown`})}).catch((e)=>x2.dispatch({kind:"system",text:`error: ${e.message}`}))})},[gw,dialog,toast,themeCtx,renderer,destructive,applyTitle,runCompress,branch2]);return import_react128.useEffect(()=>cmd.register([{title:"Help",value:"help",action:"help.open",category:"General",onSelect:()=>dialog.replace($jsx(HelpDialog,{}))},{title:"Keybindings",value:"keys",description:"View & rebind shortcuts",category:"General",onSelect:()=>openKeys(dialog)},{title:"Gateway Logs",value:"logs",description:"Show gateway stderr",category:"General",onSelect:()=>openLogs(dialog)},{title:"Switch Theme",value:"theme",action:"theme.pick",category:"General",onSelect:()=>openThemePicker(dialog,themeCtx)},{title:"Switch Model",value:"model",action:"model.pick",category:"General",onSelect:()=>openModelPicker(dialog,gw)},{title:"Pick Avatar",value:"eikon",description:"Choose sidebar .eikon avatar",category:"General",onSelect:()=>pickEikon()},{title:"Rollback",value:"rollback",description:"Browse & restore checkpoints",category:"Session",onSelect:()=>openRollback(dialog,gw,toast)},{title:"History",value:"history",action:"session.timeline",category:"Session",onSelect:()=>openHistory(dialog,gw)},{title:"Status",value:"status",action:"status.open",category:"Info",onSelect:()=>openStatus(dialog,ctx2.current.info,ctx2.current.sid)},{title:"Usage",value:"usage",description:"Tokens \xB7 context \xB7 cost",category:"Info",onSelect:()=>openUsage(dialog,gw)},{title:"Profile",value:"profile",description:"Active profile details",category:"Info",onSelect:()=>openProfile(dialog)},{title:"New Session",value:"new-session",action:"session.new",category:"Session",onSelect:()=>destructive("",{title:"Start a new session?",body:"Ends the current session and starts a fresh one. The existing session remains saved and resumable.",yes:"new session"},()=>{ctx2.current.newSession()})},{title:"Compress Session",value:"compress",action:"session.compress",category:"Session",onSelect:()=>runCompress()},{title:"Undo Last Turn",value:"undo",description:"Pop last user+assistant pair",category:"Session",onSelect:()=>run({name:"undo",target:"local"})},{title:"Redo",value:"redo",action:"session.redo",category:"Session",onSelect:()=>run({name:"redo",target:"local"})},{title:"Branch Session",value:"branch",description:"Fork the current conversation",category:"Session",onSelect:()=>branch2()}]),[cmd,dialog,themeCtx,gw,toast,destructive,pickEikon,runCompress,branch2,run]),run}var import_react132=__toESM(require_react_production(),1);var import_react130=__toESM(require_react_production(),1);function openAlert(dialog,title,body2){dialog.replace($jsx(Alert,{title,body:body2,onClose:()=>dialog.clear()}))}var Alert=(props)=>{let theme=useTheme().theme,keys=useKeys(),[copied,setCopied]=import_react130.useState(!1),doCopy=()=>{copy(props.body),setCopied(!0),setTimeout(()=>setCopied(!1),900)};return useKeyboard((key5)=>{if(keys.match("dialog.cancel",key5)||keys.match("dialog.accept",key5))props.onClose();if(keys.match("dialog.copy",key5))doCopy()}),$jsxs("box",{flexDirection:"column",width:84,maxHeight:28,border:["left"],borderColor:theme.info,customBorderChars:LEFT_BAR,backgroundColor:theme.backgroundPanel,paddingLeft:2,paddingRight:2,paddingY:1,gap:1,children:[$jsx("box",{height:1,children:$jsxs("text",{children:[$jsx("span",{fg:theme.info,children:"\u25C8 "}),$jsx("span",{fg:theme.text,children:props.title})]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.body})}),$jsxs("box",{height:1,flexDirection:"row",children:[$jsx("box",{flexShrink:0,children:$jsx("text",{fg:theme.textMuted,children:`${keys.print("dialog.cancel")} close \xB7 ${keys.print("dialog.copy")} `})}),$jsx("box",{flexShrink:0,onMouseDown:(e)=>{e.stopPropagation(),doCopy()},children:$jsx("text",{fg:copied?theme.success:theme.textMuted,children:$jsx("u",{children:copied?"copied":"copy"})})})]})]})};init_perf();function variant(level2){switch(level2){case"error":return"error";case"warning":case"warn":return"warning";case"success":return"success";default:return"info"}}function duration2(p){if(p.kind==="sticky")return null;if(typeof p.ttl_ms==="number")return p.ttl_ms;if(typeof p.duration_ms==="number")return p.duration_ms;return}function showNotification(toast,p){let text4=String(p?.text??"").trim();if(!text4)return;toast.show({key:p?.key,variant:variant(p?.level),message:text4,duration:duration2(p??{text:text4})})}function clearNotification(toast,p){let key5=String(p?.key??"").trim();if(!key5)return;toast.clear(key5)}function count3(o){return o?Object.values(o).reduce((n,v2)=>n+v2.length,0):0}function formatProcessNotification(text4){let body2=text4.replace(/^\[IMPORTANT: /,"").replace(/\]$/,""),done2=body2.match(/^Background process (\S+) completed \(exit code (\S+)\)\.\nCommand: (.+?)(?:\n|$)/);if(done2)return`${done2[1]} exited ${done2[2]} \xB7 ${done2[3]}`;let hit2=body2.match(/^Background process (\S+) matched watch pattern "([^"]+)"\.\nCommand: (.+?)(?:\n|$)/);if(hit2)return`${hit2[1]} matched "${hit2[2]}" \xB7 ${hit2[3]}`;return body2.slice(0,100)}function mapEvent(ev,side){switch(ev.type){case"gateway.ready":if(side.onReady?.(),ev.payload?.skin)side.onSkin?.(ev.payload.skin);return null;case"session.info":{let si=ev.payload;side.onSessionInfo?.(si);let label2=si.model?`Connected \u2014 ${si.model} \xB7 ${count3(si.tools)} tools \xB7 ${count3(si.skills)} skills`:"Connected to Hermes";if(si.credential_warning)side.onStatus?.(si.credential_warning);return{kind:"system",text:label2}}case"message.start":return count("stream:start"),mem("stream-start"),{kind:"message.start"};case"message.delta":{let chunk=ev.payload?.text??"";if(!chunk)return null;return count("stream:chunk"),{kind:"message.delta",chunk}}case"message.complete":{count("stream:done"),mem("stream-done");let p=ev.payload;if(p?.usage)side.onUsage?.(p.usage);if(side.onTurnComplete?.(),p?.status==="error")return{kind:"error",text:p.text||"request failed \u2014 see messages above"};if(p?.status==="interrupted")return{kind:"message.complete",text:(p.text||"")+`
|
|
4191
4193
|
|
|
4192
4194
|
*[interrupted]*`,usage:p?.usage};return{kind:"message.complete",text:p?.text??void 0,usage:p?.usage}}case"tool.start":return{kind:"tool.start",id:ev.payload.tool_id,name:ev.payload.name??"unknown",preview:ev.payload.context,args:ev.payload.args_text};case"tool.progress":return{kind:"tool.progress",name:ev.payload.name,preview:ev.payload.preview};case"tool.generating":return{kind:"tool.generating",name:ev.payload.name};case"tool.complete":return{kind:"tool.complete",id:ev.payload.tool_id,summary:ev.payload.summary,error:ev.payload.error,inline_diff:ev.payload.inline_diff,duration:typeof ev.payload.duration_s==="number"?ev.payload.duration_s*1000:void 0,result:ev.payload.result_text};case"thinking.delta":return side.onStatus?.(ev.payload?.text??""),null;case"reasoning.delta":case"reasoning.available":{let text4=ev.payload?.text;if(!text4)return null;return{kind:"thinking",text:text4,final:ev.type==="reasoning.available",verbose:ev.payload?.verbose}}case"subagent.start":case"subagent.thinking":case"subagent.tool":case"subagent.progress":case"subagent.complete":{let sub2=ev.type.slice(9);return record(sub2,ev.payload),{kind:"subagent",event:sub2,payload:ev.payload}}case"error":return{kind:"error",text:ev.payload?.message??"Unknown error"};case"clarify.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"clarify",...ev.payload}};case"approval.request":if(shouldRemember({variant:"approval",...ev.payload}))return side.onApprovalRemembered?.(),null;return{kind:"prompt",id:`approval-${pid()}`,req:{variant:"approval",...ev.payload}};case"sudo.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"sudo",...ev.payload}};case"secret.request":return{kind:"prompt",id:ev.payload.request_id,req:{variant:"secret",...ev.payload}};case"background.complete":return side.onBackground?.(ev.payload.task_id,ev.payload.text),null;case"review.summary":{let text4=String(ev.payload?.text??"").trim();if(!text4)return null;return{kind:"system",text:text4}}case"btw.complete":return side.onBtw?.(ev.payload.text),null;case"gateway.stderr":{let line4=ev.payload.line;if(/error|fail|traceback|exception|\b[45]\d\d\b|refused|denied|unauthori/i.test(line4))return{kind:"error",text:line4,fatal:!1};return null}case"skin.changed":return side.onSkin?.(ev.payload),null;case"gateway.start_timeout":return{kind:"error",text:`gateway startup timed out (${ev.payload?.python??"python"} @ ${ev.payload?.cwd??"?"})`};case"gateway.protocol_error":return{kind:"system",text:`protocol error: ${ev.payload?.preview??"?"}`};case"browser.progress":{let text4=ev.payload?.message??"";if(!text4)return null;return ev.payload?.level==="error"?{kind:"error",text:text4}:{kind:"system",text:`\xB7 ${text4}`}}case"status.update":{let kind2=ev.payload?.kind,text4=ev.payload?.text??"";if(side.onStatus?.(text4),!kind2||kind2==="status")return null;if(kind2==="process")return side.onProcessNotification?.(text4),null;return{kind:"system",text:text4}}case"notification.show":if(side.notices)showNotification(side.notices,ev.payload);return null;case"notification.clear":if(side.notices)clearNotification(side.notices,ev.payload);return null;case"voice.status":{let state2=String(ev.payload?.state??"");return side.onVoiceStatus?.(state2),null}case"voice.transcript":{if(ev.payload?.no_speech_limit===!0)return side.onVoiceTranscript?.("",!0),null;let text4=String(ev.payload?.text??"").trim();if(!text4)return null;return side.onVoiceTranscript?.(text4,!1),null}}return null}var STREAM_EVENTS=new Set(["message.start","message.delta","reasoning.delta","reasoning.available","thinking.delta","tool.start","tool.progress","tool.generating"]),TITLE_DELAYS=[1200,5000,15000,30000];function useStream(c){let gw=useGateway(),dialog=useDialog(),toast=useToast(),bg2=useBackground(),ctx2=import_react132.useRef(c);ctx2.current=c;let timers=import_react132.useRef([]);import_react132.useEffect(()=>()=>{timers.current.forEach(clearTimeout),timers.current=[]},[]);let interrupted=import_react132.useRef(!1),info2=import_react132.useRef(!1),deltas=import_react132.useRef({text:"",think:"",timer:null}),procs=import_react132.useRef({texts:[],timer:null}),flush2=import_react132.useCallback(()=>{let d2=deltas.current;if(d2.timer)clearTimeout(d2.timer),d2.timer=null;if(d2.think)ctx2.current.dispatch({kind:"thinking",text:d2.think,final:!1}),d2.think="";if(d2.text)ctx2.current.dispatch({kind:"message.delta",chunk:d2.text}),d2.text=""},[]),flushProcs=import_react132.useCallback(()=>{let n=procs.current;if(n.timer)clearTimeout(n.timer),n.timer=null;if(!n.texts.length)return;let batch=n.texts.splice(0),lines3=batch.map((t2)=>` ${formatProcessNotification(t2)}`);ctx2.current.dispatch({kind:"system",text:batch.length===1?`\u25C6 background ${lines3[0].trim()}`:`\u25C6 ${batch.length} background notifications
|
|
4193
4195
|
${lines3.join(`
|
|
@@ -4198,19 +4200,19 @@ ${lines3.join(`
|
|
|
4198
4200
|
`):frame2;if(url2.searchParams.get("json")==="1")return json({frame:body2,match:grep?frame2.includes(grep):void 0,lines:frame2.split(`
|
|
4199
4201
|
`).length});return new Response(body2,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}if(path7==="/logs"){let n=Number(url2.searchParams.get("n"))||200;return new Response(bridge.logs(n),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}let pm=path7.match(/^\/plugin\/([^/]+)$/);if(pm&&req.method==="POST"){let body2=await req.json(),ok=await bridge.plugin(pm[1],body2.on!==!1);return json({id:pm[1],on:body2.on!==!1,ok})}if(path7==="/push"&&req.method==="POST"){let body2=await req.json();if(!body2.type)return json({error:"type required"},400);return bridge.push(body2),json({pushed:body2.type})}if(path7==="/perf"){let d2=data();if(!d2)return json({error:"PERF not enabled"},400);return json(d2)}if(path7==="/tabs"){let ms2=Number(url2.searchParams.get("delay")||"500");for(let i=0;i<=TAB_MAX;i++)bridge.setTab(i),await new Promise((r)=>setTimeout(r,ms2));return bridge.setTab(CHAT_TAB),json({cycled:TAB_MAX+1,delay:ms2})}if(path7==="/mem"){mem("control:snapshot");let m2=process.memoryUsage();return json({rss:Math.round(m2.rss/1024/1024),heap:Math.round(m2.heapUsed/1024/1024),heapTotal:Math.round(m2.heapTotal/1024/1024),external:Math.round(m2.external/1024/1024)})}return json({error:"not found",routes:["GET /status","GET /tab/:n","POST /send {message}","POST /key {name, ctrl?, shift?, meta?, raw?, safe?}","POST /keys {keys: [{name, ...}], delay?, safe?}","POST /type {text, delay?, safe?}","POST /input {text}","POST /plugin/:id {on}","POST /push {type, payload?}","GET /quit","GET /frame ?grep=pat&json=1","GET /logs ?n=200","GET /focus","GET /perf","GET /tabs","GET /mem"]},404)}function start(){if(!enabled2)return;Bun.serve({port:PORT,hostname:BIND,fetch:handle});let w2=warning();if(w2){process.stderr.write(`\x1B[33m[control] WARNING: ${w2.message}\x1B[0m
|
|
4200
4202
|
`);return}process.stderr.write(`\x1B[90m[control] http://${BIND}:${PORT}\x1B[0m
|
|
4201
|
-
`)}var import_react136=__toESM(require_react_production(),1);function select(dialog,opts){return new Promise((res)=>{let settled=!1,done2=(v2)=>{if(settled)return;settled=!0,res(v2),dialog.clear()};dialog.replace($jsx(DialogSelect,{title:opts.title,options:opts.options,placeholder:opts.placeholder,onSelect:(o)=>done2(o)}),()=>done2(null))})}function locate3(routes,name){let lower=name.toLowerCase(),hit2=TAB_SLASH[lower];if(hit2)return hit2;let i=[...routes.keys()].findIndex((n)=>n.toLowerCase()===lower);if(i<0)return;return{tab:TABS.length+i,sub:0}}function createApi(input){return{renderer:input.renderer,theme:{get current(){return input.theme.current.theme},get name(){return input.theme.current.name},get mode(){return input.theme.current.mode},set:(name)=>input.theme.current.set(name),setMode:(mode)=>input.theme.current.setMode(mode),has:(name)=>input.theme.current.has(name)},get keys(){return input.keys.current},ui:{dialog:input.dialog,toast:(o)=>input.toast.show({variant:o.variant??"info",title:o.title,message:o.message}),confirm:(o)=>openConfirm(input.dialog,o),prompt:(o)=>openTextPrompt(input.dialog,o),alert:(title,body2)=>openAlert(input.dialog,title,body2),select:(o)=>select(input.dialog,o)},kv:{get:(key5,fallback)=>{return get2("plugin")?.[key5]??fallback},set:(key5,value)=>{let bag=get2("plugin")??{};set("plugin",{...bag,[key5]:value})}},get client(){return input.gw.current},event:{on:(fn)=>{let c=input.gw.current,h2=(ev)=>fn(ev);return c.on("event",h2),()=>c.off("event",h2)}},route:{register:(defs)=>{for(let d2 of defs)input.routes.set(d2.name,d2);return input.bump(),()=>{for(let d2 of defs)input.routes.delete(d2.name);input.bump()}},navigate:(name,sub2)=>{let at=locate3(input.routes,name);if(!at)return;input.nav.current?.(at.tab,sub2??at.sub)},get current(){return input.cur.current?.()}},command:{register:(cmds)=>input.cmd.register(cmds)},slots:{register(){throw Error("slots.register is only available inside a plugin's tui() factory")}},eikon:{rasterizer:{register:(r)=>register(r)}},lifecycle:{signal:new AbortController().signal,onDispose:()=>()=>{}}}}function createScope(id,fail2){let ctrl=new AbortController,list3=[],done2=!1,onDispose=(fn)=>{if(done2)return()=>{};let key5=Symbol();return list3.push({key:key5,fn}),()=>{list3=list3.filter((x2)=>x2.key!==key5)}},track=(fn)=>{if(!fn)return()=>{};let ran=!1,drop2=()=>{},wrapped=()=>{if(ran)return;return ran=!0,drop2(),fn()};return drop2=onDispose(wrapped),wrapped},race=(fn,left)=>new Promise((res)=>{let t2=setTimeout(()=>res("timeout"),left);Promise.resolve().then(fn).then(()=>{clearTimeout(t2),res("ok")}).catch((e)=>{clearTimeout(t2),res(e instanceof Error?e:Error(String(e)))})}),dispose=async()=>{if(done2)return;done2=!0,ctrl.abort();let queue=[...list3].reverse();list3=[];let until2=Date.now()+5000;for(let item of queue){let left=until2-Date.now();if(left<=0){fail2(`[plugin:${id}] dispose budget exhausted`);return}let out=await race(item.fn,left);if(out==="ok")continue;if(out==="timeout"){fail2(`[plugin:${id}] dispose timed out`);return}fail2(`[plugin:${id}] dispose threw`,out)}};return{lifecycle:{signal:ctrl.signal,onDispose},track,dispose}}var import_react133=__toESM(require_react_production(),1);var fmt4=(d2)=>[d2.getHours(),d2.getMinutes(),d2.getSeconds()].map((n)=>String(n).padStart(2,"0")).join(":");function Clock(props){let[now2,set2]=import_react133.useState(()=>new Date);return import_react133.useEffect(()=>{let t2=setInterval(()=>set2(new Date),1000);return()=>clearInterval(t2)},[]),$jsx("text",{fg:props.api.theme.current.textMuted,wrapMode:"none",children:fmt4(now2)})}var plugin={id:"demo.clock",enabled:!1,tui(api){api.slots.register({order:100,slots:{app_bottom:()=>$jsx(Clock,{api})}})}},clock_default=plugin;var import_react134=__toESM(require_react_production(),1);import{readdirSync as readdirSync8,statSync as statSync7}from"fs";import{join as join25,basename as basename15}from"path";import{homedir as homedir9}from"os";var PREVIEW_MAX=200000,read3=(dir2)=>{return(dir2==="/"?[]:[{name:"..",dir:!0}]).concat(readdirSync8(dir2,{withFileTypes:!0}).filter((d2)=>!d2.name.startsWith(".")).sort((a,b2)=>a.isDirectory()===b2.isDirectory()?a.name.localeCompare(b2.name):a.isDirectory()?-1:1).map((d2)=>({name:d2.name,dir:d2.isDirectory()})))},isMd=(name)=>/\.(md|markdown|mdx)$/i.test(name);function Files(props){let api=props.api,theme=api.theme.current,[dir2,setDir]=import_react134.useState(()=>homedir9()),[sel,setSel]=import_react134.useState(0),[preview3,setPreview]=import_react134.useState(""),[err,setErr]=import_react134.useState(""),rows3=import_react134.useMemo(()=>{setErr("");try{return read3(dir2)}catch(e){return setErr(String(e.message??e)),[]}},[dir2]);import_react134.useEffect(()=>{setSel((s)=>Math.min(s,Math.max(0,rows3.length-1)))},[rows3.length]);let active=rows3[sel];import_react134.useEffect(()=>{if(!active||active.dir){setPreview("");return}let path7=join25(dir2,active.name),cancel=!1;return(async()=>{let st=statSync7(path7);if(st.size>PREVIEW_MAX){if(!cancel)setPreview(`(file too large \u2014 ${st.size} bytes)`);return}let text4=await Bun.file(path7).text();if(!cancel)setPreview(text4)})().catch((e)=>{if(!cancel)setPreview(`(read error: ${e})`)}),()=>{cancel=!0}},[dir2,active?.name,active?.dir]);let enter=()=>{if(!active)return;if(active.name===".."){setDir((d2)=>d2==="/"?"/":join25(d2,"..")),setSel(0);return}if(active.dir)setDir((d2)=>join25(d2,active.name)),setSel(0)};return useKeyboard((key5)=>{if(key5.name==="left"){setDir((d2)=>d2==="/"?"/":join25(d2,"..")),setSel(0);return}handleListKey(api.keys,key5,{count:rows3.length,setSel,onActivate:enter})}),$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:dir2})}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{width:32,flexShrink:0,flexDirection:"column",border:!0,borderColor:theme.border,children:[rows3.map((e,i)=>$jsx("box",{height:1,paddingX:1,backgroundColor:i===sel?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===sel?theme.selectedListItemText:e.dir?theme.accent:theme.text,wrapMode:"none",children:(e.dir?"\u25B8 ":" ")+e.name})},e.name)),err?$jsx("box",{height:1,paddingX:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",children:err})}):null]}),$jsx("box",{flexGrow:1,flexDirection:"column",border:!0,borderColor:theme.border,children:active&&!active.dir?$jsxs($Fragment,{children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[basename15(active.name),isMd(active.name)?" \xB7 markdown":""]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:preview3})})]}):$jsx("box",{paddingX:1,children:$jsx("text",{fg:theme.textMuted,children:"Select a file to preview."})})})]})]})}var plugin2={id:"demo.files",enabled:!1,tui(api){api.route.register([{name:"Files",description:"File browser",render:()=>$jsx(Files,{api})}]),api.command.register([{title:"Files: open browser",value:"plugin.files.open",category:"Plugin",onSelect:()=>api.route.navigate("Files")}])}},files_default=plugin2;var INTERNAL=[clock_default,files_default];var KV_ENABLED="enabled",Ctx7=import_react136.createContext(null);function fail2(msg,err){let tail=err instanceof Error?`: ${err.message}`:err!==void 0?`: ${String(err)}`:"";console.error(msg+tail)}function enabledMap(){let v2=get2("plugin")?.[KV_ENABLED];return v2&&typeof v2==="object"?v2:{}}function persist2(id,on){let bag=get2("plugin")??{},map={...enabledMap(),[id]:on};set("plugin",{...bag,[KV_ENABLED]:map})}function scoped(base2,reg,id,scope){let n=0;return{...base2,slots:{register(p){let sid2=n++?`${id}:${n}`:id;return scope.track(reg.register({...p,id:sid2}))}},route:{register:(defs)=>scope.track(base2.route.register(defs)),navigate:base2.route.navigate,get current(){return base2.route.current}},event:{on:(fn)=>scope.track(base2.event.on(fn))},command:{register:(cmds)=>scope.track(base2.command.register(cmds))},eikon:{rasterizer:{register:(r)=>scope.track(base2.eikon.rasterizer.register(r))}},kv:{get:(key5,fb)=>base2.kv.get(`${id}.${key5}`,fb),set:(key5,v2)=>base2.kv.set(`${id}.${key5}`,v2)},lifecycle:scope.lifecycle}}var CELLS=new WeakMap;function ctxFor(renderer,themeRef){let hit2=CELLS.get(renderer);if(hit2)return hit2.themeRef=themeRef,hit2.ctx;let cell={themeRef,ctx:{}};return Object.defineProperty(cell.ctx,"theme",{get:()=>cell.themeRef.current.theme,enumerable:!0}),CELLS.set(renderer,cell),cell.ctx}function PluginProvider(props){let list3=props.plugins??INTERNAL,renderer=useRenderer(),themeCtx=useTheme(),keys=useKeys(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),gw=useGateway(),themeRef=import_react136.useRef(themeCtx);themeRef.current=themeCtx;let keysRef=import_react136.useRef(keys);keysRef.current=keys;let gwRef=import_react136.useRef(gw);gwRef.current=gw;let navRef=import_react136.useRef(null),curRef=import_react136.useRef(null),routes=import_react136.useRef(new Map).current,[rev2,bump2]=import_react136.useReducer((x2)=>x2+1,0),reg=import_react136.useMemo(()=>createReactSlotRegistry(renderer,ctxFor(renderer,themeRef),{onPluginError:(e)=>fail2(`[plugin:${e.pluginId}] ${e.phase} error in slot "${e.slot}"`,e.error)}),[renderer]),Slot2=import_react136.useMemo(()=>createSlot(reg),[reg]),api=import_react136.useMemo(()=>createApi({renderer,theme:themeRef,keys:keysRef,dialog,toast,gw:gwRef,cmd,routes,bump:bump2,nav:navRef,cur:curRef}),[renderer,dialog,toast,cmd,routes]),entries2=import_react136.useRef(new Map),[gen,force]=import_react136.useReducer((x2)=>x2+1,0),activate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!0,write)persist2(id,!0);if(e.scope)return!0;let scope=createScope(id,fail2),ok=await Promise.resolve().then(()=>e.plugin.tui(scoped(api,reg,id,scope))).then(()=>!0).catch((err)=>{return fail2(`[plugin:${id}] activation failed`,err),e.error=String(err?.message??err),!1});if(!ok||!e.enabled)return await scope.dispose(),force(),ok&&!0;return e.scope=scope,e.error=void 0,force(),!0},deactivate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!1,write)persist2(id,!1);let scope=e.scope;if(e.scope=void 0,scope)await scope.dispose();return force(),!0},started=import_react136.useRef(!1);import_react136.useEffect(()=>{if(started.current)return;started.current=!0;let on=enabledMap();for(let p of list3)entries2.current.set(p.id,{plugin:p,enabled:on[p.id]??p.enabled??!0});return(async()=>{for(let[id,e]of entries2.current)if(e.enabled)await activate(id,!1)})(),()=>{for(let[,e]of entries2.current)e.scope?.dispose();entries2.current.clear(),routes.clear(),reg.clear()}},[]);let value=import_react136.useMemo(()=>({Slot:Slot2,routes:[...routes.values()],bind:(nav,current2)=>{navRef.current=nav,curRef.current=current2},status:()=>[...entries2.current.values()].map((e)=>({id:e.plugin.id,enabled:e.enabled,active:!!e.scope,error:e.error})),has:(slot2)=>reg.resolveEntries(slot2).length>0,activate:(id)=>activate(id),deactivate:(id)=>deactivate(id)}),[Slot2,routes,rev2,gen]);return $jsx(Ctx7.Provider,{value,children:props.children})}var usePlugins=makeUse(Ctx7,"usePlugins");function useBridge(o){let gw=useGateway(),renderer=useRenderer(),plugins=usePlugins(),state2=import_react138.useRef(o);state2.current=o,import_react138.useEffect(()=>{if(!enabled2)return;setBridge({tab:()=>state2.current.tab,setTab:o.setTab,send:(msg)=>{let s=state2.current;if(!s.ready||s.streaming)return;s.dispatch({kind:"user",text:msg}),gw.request("prompt.submit",{text:msg}).catch(()=>{}),s.setTab(CHAT_TAB)},ready:()=>state2.current.ready,streaming:()=>state2.current.streaming,messages:()=>state2.current.messages.length,session:()=>state2.current.sid,input:()=>state2.current.composer.current?.value()??"",setInput:(v2)=>state2.current.composer.current?.set(v2),focusRegion:()=>state2.current.focusRegion,setFocusRegion:o.setFocusRegion,renderer:()=>renderer,logs:(n)=>gw.tail(n),plugin:(id,on)=>on?plugins.activate(id):plugins.deactivate(id),push:(ev)=>gw.emit("event",ev)})},[gw,renderer,plugins])}var import_react146=__toESM(require_react_production(),1);var winDrive=(s,off=0)=>s.length>=off+3&&/[A-Za-z]/.test(s[off])&&s[off+1]===":"&&(s[off+2]==="\\"||s[off+2]==="/");function looksLikePath(s){let t2=s.trim();if(!t2||t2.includes(`
|
|
4202
|
-
`))return!1;if(t2.startsWith("file://"))return!0;if(t2.startsWith("/")||t2.startsWith("~")||t2.startsWith("./")||t2.startsWith("../"))return!0;if(winDrive(t2))return!0;let q5=t2[0];if(q5==='"'||q5==="'"){let inner=t2[1];if(inner==="/"||inner==="~")return!0;if(winDrive(t2,1))return!0}return!1}var import_react140=__toESM(require_react_production(),1);var SEP=new Set(["-","_","/"," ","."]);function boundary(hay,i){if(i===0)return!0;let prev=hay[i-1];if(SEP.has(prev))return!0;if(prev===prev.toLowerCase()&&hay[i]!==hay[i].toLowerCase())return!0;return!1}function score(needle,hay){if(!needle)return 0;let n=needle.toLowerCase(),h2=hay.toLowerCase(),pts=0,from2=0,prev=-2;for(let i=0;i<n.length;i++){let at=h2.indexOf(n[i],from2);if(at<0)return 0;if(pts+=1,at===0)pts+=8;if(at===prev+1)pts+=5;if(at!==prev+1&&boundary(hay,at))pts+=4;pts-=(at-(prev<0?0:prev+1))*0.1,prev=at,from2=at+1}if(h2.startsWith(n))pts+=100;return pts-hay.length*0.01}function best(q5,cmd){return cmd.aliases.reduce((m2,a)=>Math.max(m2,score(q5,a)),score(q5,cmd.name))}function rank(list3,q5){if(!q5)return[...list3];return list3.map((cmd)=>({cmd,s:best(q5,cmd)})).filter((r)=>r.s>0).sort((a,b2)=>b2.s-a.s).map((r)=>r.cmd)}function useSlashPopover(input,cmds){let[cursor,setCursor]=import_react140.useState(0),popover=import_react140.useMemo(()=>{let subs3=matchSub(cmds,input);if(subs3)return subs3;let m2=input.match(/^\/(\S*)$/);return m2?rank(cmds,m2[1]):null},[input,cmds]),active=popover?Math.max(0,Math.min(cursor,popover.length-1)):0;import_react140.useEffect(()=>{setCursor((c)=>c===0?c:0)},[input]);let ghost=import_react140.useMemo(()=>{if(!popover||popover.length===0)return"";let best2=popover[active];if(!best2||best2.name.includes(" "))return"";let m2=input.match(/^\/(\S*)$/);if(!m2)return"";let typed=m2[1];if(typed.length<2)return"";if(!best2.name.toLowerCase().startsWith(typed.toLowerCase()))return"";return best2.name.slice(typed.length)},[input,popover,active]),open2=popover!==null&&popover.length>0;return{popover,cursor:active,setCursor,ghost,open:open2}}var import_react141=__toESM(require_react_production(),1);var exports_frecency={};__export(exports_frecency,{score:()=>score2,frecency:()=>exports_frecency,bump:()=>bump2,_reset:()=>_reset});import{join as join26}from"path";import{existsSync as
|
|
4203
|
-
`).filter(Boolean).map((l)=>{try{return JSON.parse(l)}catch{return null}}).filter((e)=>e!==null),latest2={};for(let e of rows3)latest2[e.path]=e;let kept=Object.values(latest2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);if(kept.length<rows3.length)
|
|
4203
|
+
`)}var import_react136=__toESM(require_react_production(),1);function select(dialog,opts){return new Promise((res)=>{let settled=!1,done2=(v2)=>{if(settled)return;settled=!0,res(v2),dialog.clear()};dialog.replace($jsx(DialogSelect,{title:opts.title,options:opts.options,placeholder:opts.placeholder,onSelect:(o)=>done2(o)}),()=>done2(null))})}function locate3(routes,name){let lower=name.toLowerCase(),hit2=TAB_SLASH[lower];if(hit2)return hit2;let i=[...routes.keys()].findIndex((n)=>n.toLowerCase()===lower);if(i<0)return;return{tab:TABS.length+i,sub:0}}function createApi(input){return{renderer:input.renderer,theme:{get current(){return input.theme.current.theme},get name(){return input.theme.current.name},get mode(){return input.theme.current.mode},set:(name)=>input.theme.current.set(name),setMode:(mode)=>input.theme.current.setMode(mode),has:(name)=>input.theme.current.has(name)},get keys(){return input.keys.current},ui:{dialog:input.dialog,toast:(o)=>input.toast.show({variant:o.variant??"info",title:o.title,message:o.message}),confirm:(o)=>openConfirm(input.dialog,o),prompt:(o)=>openTextPrompt(input.dialog,o),alert:(title,body2)=>openAlert(input.dialog,title,body2),select:(o)=>select(input.dialog,o)},kv:{get:(key5,fallback)=>{return get2("plugin")?.[key5]??fallback},set:(key5,value)=>{let bag=get2("plugin")??{};set("plugin",{...bag,[key5]:value})}},get client(){return input.gw.current},event:{on:(fn)=>{let c=input.gw.current,h2=(ev)=>fn(ev);return c.on("event",h2),()=>c.off("event",h2)}},route:{register:(defs)=>{for(let d2 of defs)input.routes.set(d2.name,d2);return input.bump(),()=>{for(let d2 of defs)input.routes.delete(d2.name);input.bump()}},navigate:(name,sub2)=>{let at=locate3(input.routes,name);if(!at)return;input.nav.current?.(at.tab,sub2??at.sub)},get current(){return input.cur.current?.()}},command:{register:(cmds)=>input.cmd.register(cmds)},slots:{register(){throw Error("slots.register is only available inside a plugin's tui() factory")}},eikon:{rasterizer:{register:(r)=>register(r)}},lifecycle:{signal:new AbortController().signal,onDispose:()=>()=>{}}}}function createScope(id,fail2){let ctrl=new AbortController,list3=[],done2=!1,onDispose=(fn)=>{if(done2)return()=>{};let key5=Symbol();return list3.push({key:key5,fn}),()=>{list3=list3.filter((x2)=>x2.key!==key5)}},track=(fn)=>{if(!fn)return()=>{};let ran=!1,drop2=()=>{},wrapped=()=>{if(ran)return;return ran=!0,drop2(),fn()};return drop2=onDispose(wrapped),wrapped},race=(fn,left)=>new Promise((res)=>{let t2=setTimeout(()=>res("timeout"),left);Promise.resolve().then(fn).then(()=>{clearTimeout(t2),res("ok")}).catch((e)=>{clearTimeout(t2),res(e instanceof Error?e:Error(String(e)))})}),dispose=async()=>{if(done2)return;done2=!0,ctrl.abort();let queue=[...list3].reverse();list3=[];let until2=Date.now()+5000;for(let item of queue){let left=until2-Date.now();if(left<=0){fail2(`[plugin:${id}] dispose budget exhausted`);return}let out=await race(item.fn,left);if(out==="ok")continue;if(out==="timeout"){fail2(`[plugin:${id}] dispose timed out`);return}fail2(`[plugin:${id}] dispose threw`,out)}};return{lifecycle:{signal:ctrl.signal,onDispose},track,dispose}}var import_react133=__toESM(require_react_production(),1);var fmt4=(d2)=>[d2.getHours(),d2.getMinutes(),d2.getSeconds()].map((n)=>String(n).padStart(2,"0")).join(":");function Clock(props){let[now2,set2]=import_react133.useState(()=>new Date);return import_react133.useEffect(()=>{let t2=setInterval(()=>set2(new Date),1000);return()=>clearInterval(t2)},[]),$jsx("text",{fg:props.api.theme.current.textMuted,wrapMode:"none",children:fmt4(now2)})}var plugin={id:"demo.clock",enabled:!1,tui(api){api.slots.register({order:100,slots:{app_bottom:()=>$jsx(Clock,{api})}})}},clock_default=plugin;var import_react134=__toESM(require_react_production(),1);import{readdirSync as readdirSync8,statSync as statSync7}from"fs";import{join as join25,basename as basename16}from"path";import{homedir as homedir9}from"os";var PREVIEW_MAX=200000,read3=(dir2)=>{return(dir2==="/"?[]:[{name:"..",dir:!0}]).concat(readdirSync8(dir2,{withFileTypes:!0}).filter((d2)=>!d2.name.startsWith(".")).sort((a,b2)=>a.isDirectory()===b2.isDirectory()?a.name.localeCompare(b2.name):a.isDirectory()?-1:1).map((d2)=>({name:d2.name,dir:d2.isDirectory()})))},isMd=(name)=>/\.(md|markdown|mdx)$/i.test(name);function Files(props){let api=props.api,theme=api.theme.current,[dir2,setDir]=import_react134.useState(()=>homedir9()),[sel,setSel]=import_react134.useState(0),[preview2,setPreview]=import_react134.useState(""),[err,setErr]=import_react134.useState(""),rows3=import_react134.useMemo(()=>{setErr("");try{return read3(dir2)}catch(e){return setErr(String(e.message??e)),[]}},[dir2]);import_react134.useEffect(()=>{setSel((s)=>Math.min(s,Math.max(0,rows3.length-1)))},[rows3.length]);let active=rows3[sel];import_react134.useEffect(()=>{if(!active||active.dir){setPreview("");return}let path7=join25(dir2,active.name),cancel=!1;return(async()=>{let st=statSync7(path7);if(st.size>PREVIEW_MAX){if(!cancel)setPreview(`(file too large \u2014 ${st.size} bytes)`);return}let text4=await Bun.file(path7).text();if(!cancel)setPreview(text4)})().catch((e)=>{if(!cancel)setPreview(`(read error: ${e})`)}),()=>{cancel=!0}},[dir2,active?.name,active?.dir]);let enter=()=>{if(!active)return;if(active.name===".."){setDir((d2)=>d2==="/"?"/":join25(d2,"..")),setSel(0);return}if(active.dir)setDir((d2)=>join25(d2,active.name)),setSel(0)};return useKeyboard((key5)=>{if(key5.name==="left"){setDir((d2)=>d2==="/"?"/":join25(d2,"..")),setSel(0);return}handleListKey(api.keys,key5,{count:rows3.length,setSel,onActivate:enter})}),$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:dir2})}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{width:32,flexShrink:0,flexDirection:"column",border:!0,borderColor:theme.border,children:[rows3.map((e,i)=>$jsx("box",{height:1,paddingX:1,backgroundColor:i===sel?theme.backgroundElement:void 0,children:$jsx("text",{fg:i===sel?theme.selectedListItemText:e.dir?theme.accent:theme.text,wrapMode:"none",children:(e.dir?"\u25B8 ":" ")+e.name})},e.name)),err?$jsx("box",{height:1,paddingX:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",children:err})}):null]}),$jsx("box",{flexGrow:1,flexDirection:"column",border:!0,borderColor:theme.border,children:active&&!active.dir?$jsxs($Fragment,{children:[$jsx("box",{height:1,flexShrink:0,paddingX:1,children:$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[basename16(active.name),isMd(active.name)?" \xB7 markdown":""]})}),$jsx("scrollbox",{scrollY:!0,flexGrow:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:preview2})})]}):$jsx("box",{paddingX:1,children:$jsx("text",{fg:theme.textMuted,children:"Select a file to preview."})})})]})]})}var plugin2={id:"demo.files",enabled:!1,tui(api){api.route.register([{name:"Files",description:"File browser",render:()=>$jsx(Files,{api})}]),api.command.register([{title:"Files: open browser",value:"plugin.files.open",category:"Plugin",onSelect:()=>api.route.navigate("Files")}])}},files_default=plugin2;var INTERNAL=[clock_default,files_default];var KV_ENABLED="enabled",Ctx7=import_react136.createContext(null);function fail2(msg,err){let tail=err instanceof Error?`: ${err.message}`:err!==void 0?`: ${String(err)}`:"";console.error(msg+tail)}function enabledMap(){let v2=get2("plugin")?.[KV_ENABLED];return v2&&typeof v2==="object"?v2:{}}function persist2(id,on){let bag=get2("plugin")??{},map={...enabledMap(),[id]:on};set("plugin",{...bag,[KV_ENABLED]:map})}function scoped(base2,reg,id,scope){let n=0;return{...base2,slots:{register(p){let sid2=n++?`${id}:${n}`:id;return scope.track(reg.register({...p,id:sid2}))}},route:{register:(defs)=>scope.track(base2.route.register(defs)),navigate:base2.route.navigate,get current(){return base2.route.current}},event:{on:(fn)=>scope.track(base2.event.on(fn))},command:{register:(cmds)=>scope.track(base2.command.register(cmds))},eikon:{rasterizer:{register:(r)=>scope.track(base2.eikon.rasterizer.register(r))}},kv:{get:(key5,fb)=>base2.kv.get(`${id}.${key5}`,fb),set:(key5,v2)=>base2.kv.set(`${id}.${key5}`,v2)},lifecycle:scope.lifecycle}}var CELLS=new WeakMap;function ctxFor(renderer,themeRef){let hit2=CELLS.get(renderer);if(hit2)return hit2.themeRef=themeRef,hit2.ctx;let cell={themeRef,ctx:{}};return Object.defineProperty(cell.ctx,"theme",{get:()=>cell.themeRef.current.theme,enumerable:!0}),CELLS.set(renderer,cell),cell.ctx}function PluginProvider(props){let list3=props.plugins??INTERNAL,renderer=useRenderer(),themeCtx=useTheme(),keys=useKeys(),dialog=useDialog(),toast=useToast(),cmd=useCommand(),gw=useGateway(),themeRef=import_react136.useRef(themeCtx);themeRef.current=themeCtx;let keysRef=import_react136.useRef(keys);keysRef.current=keys;let gwRef=import_react136.useRef(gw);gwRef.current=gw;let navRef=import_react136.useRef(null),curRef=import_react136.useRef(null),routes=import_react136.useRef(new Map).current,[rev2,bump2]=import_react136.useReducer((x2)=>x2+1,0),reg=import_react136.useMemo(()=>createReactSlotRegistry(renderer,ctxFor(renderer,themeRef),{onPluginError:(e)=>fail2(`[plugin:${e.pluginId}] ${e.phase} error in slot "${e.slot}"`,e.error)}),[renderer]),Slot2=import_react136.useMemo(()=>createSlot(reg),[reg]),api=import_react136.useMemo(()=>createApi({renderer,theme:themeRef,keys:keysRef,dialog,toast,gw:gwRef,cmd,routes,bump:bump2,nav:navRef,cur:curRef}),[renderer,dialog,toast,cmd,routes]),entries2=import_react136.useRef(new Map),[gen,force]=import_react136.useReducer((x2)=>x2+1,0),activate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!0,write)persist2(id,!0);if(e.scope)return!0;let scope=createScope(id,fail2),ok=await Promise.resolve().then(()=>e.plugin.tui(scoped(api,reg,id,scope))).then(()=>!0).catch((err)=>{return fail2(`[plugin:${id}] activation failed`,err),e.error=String(err?.message??err),!1});if(!ok||!e.enabled)return await scope.dispose(),force(),ok&&!0;return e.scope=scope,e.error=void 0,force(),!0},deactivate=async(id,write=!0)=>{let e=entries2.current.get(id);if(!e)return!1;if(e.enabled=!1,write)persist2(id,!1);let scope=e.scope;if(e.scope=void 0,scope)await scope.dispose();return force(),!0},started=import_react136.useRef(!1);import_react136.useEffect(()=>{if(started.current)return;started.current=!0;let on=enabledMap();for(let p of list3)entries2.current.set(p.id,{plugin:p,enabled:on[p.id]??p.enabled??!0});return(async()=>{for(let[id,e]of entries2.current)if(e.enabled)await activate(id,!1)})(),()=>{for(let[,e]of entries2.current)e.scope?.dispose();entries2.current.clear(),routes.clear(),reg.clear()}},[]);let value=import_react136.useMemo(()=>({Slot:Slot2,routes:[...routes.values()],bind:(nav,current2)=>{navRef.current=nav,curRef.current=current2},status:()=>[...entries2.current.values()].map((e)=>({id:e.plugin.id,enabled:e.enabled,active:!!e.scope,error:e.error})),has:(slot2)=>reg.resolveEntries(slot2).length>0,activate:(id)=>activate(id),deactivate:(id)=>deactivate(id)}),[Slot2,routes,rev2,gen]);return $jsx(Ctx7.Provider,{value,children:props.children})}var usePlugins=makeUse(Ctx7,"usePlugins");function useBridge(o){let gw=useGateway(),renderer=useRenderer(),plugins=usePlugins(),state2=import_react138.useRef(o);state2.current=o,import_react138.useEffect(()=>{if(!enabled2)return;setBridge({tab:()=>state2.current.tab,setTab:o.setTab,send:(msg)=>{let s=state2.current;if(!s.ready||s.streaming)return;s.dispatch({kind:"user",text:msg}),gw.request("prompt.submit",{text:msg}).catch(()=>{}),s.setTab(CHAT_TAB)},ready:()=>state2.current.ready,streaming:()=>state2.current.streaming,messages:()=>state2.current.messages.length,session:()=>state2.current.sid,input:()=>state2.current.composer.current?.value()??"",setInput:(v2)=>state2.current.composer.current?.set(v2),focusRegion:()=>state2.current.focusRegion,setFocusRegion:o.setFocusRegion,renderer:()=>renderer,logs:(n)=>gw.tail(n),plugin:(id,on)=>on?plugins.activate(id):plugins.deactivate(id),push:(ev)=>gw.emit("event",ev)})},[gw,renderer,plugins])}var import_react146=__toESM(require_react_production(),1);var winDrive=(s,off=0)=>s.length>=off+3&&/[A-Za-z]/.test(s[off])&&s[off+1]===":"&&(s[off+2]==="\\"||s[off+2]==="/");function looksLikePath(s){let t2=s.trim();if(!t2||t2.includes(`
|
|
4204
|
+
`))return!1;if(t2.startsWith("file://"))return!0;if(t2.startsWith("/")||t2.startsWith("~")||t2.startsWith("./")||t2.startsWith("../"))return!0;if(winDrive(t2))return!0;let q5=t2[0];if(q5==='"'||q5==="'"){let inner=t2[1];if(inner==="/"||inner==="~")return!0;if(winDrive(t2,1))return!0}return!1}var import_react140=__toESM(require_react_production(),1);var SEP=new Set(["-","_","/"," ","."]);function boundary(hay,i){if(i===0)return!0;let prev=hay[i-1];if(SEP.has(prev))return!0;if(prev===prev.toLowerCase()&&hay[i]!==hay[i].toLowerCase())return!0;return!1}function score(needle,hay){if(!needle)return 0;let n=needle.toLowerCase(),h2=hay.toLowerCase(),pts=0,from2=0,prev=-2;for(let i=0;i<n.length;i++){let at=h2.indexOf(n[i],from2);if(at<0)return 0;if(pts+=1,at===0)pts+=8;if(at===prev+1)pts+=5;if(at!==prev+1&&boundary(hay,at))pts+=4;pts-=(at-(prev<0?0:prev+1))*0.1,prev=at,from2=at+1}if(h2.startsWith(n))pts+=100;return pts-hay.length*0.01}function best(q5,cmd){return cmd.aliases.reduce((m2,a)=>Math.max(m2,score(q5,a)),score(q5,cmd.name))}function rank(list3,q5){if(!q5)return[...list3];return list3.map((cmd)=>({cmd,s:best(q5,cmd)})).filter((r)=>r.s>0).sort((a,b2)=>b2.s-a.s).map((r)=>r.cmd)}function useSlashPopover(input,cmds){let[cursor,setCursor]=import_react140.useState(0),popover=import_react140.useMemo(()=>{let subs3=matchSub(cmds,input);if(subs3)return subs3;let m2=input.match(/^\/(\S*)$/);return m2?rank(cmds,m2[1]):null},[input,cmds]),active=popover?Math.max(0,Math.min(cursor,popover.length-1)):0;import_react140.useEffect(()=>{setCursor((c)=>c===0?c:0)},[input]);let ghost=import_react140.useMemo(()=>{if(!popover||popover.length===0)return"";let best2=popover[active];if(!best2||best2.name.includes(" "))return"";let m2=input.match(/^\/(\S*)$/);if(!m2)return"";let typed=m2[1];if(typed.length<2)return"";if(!best2.name.toLowerCase().startsWith(typed.toLowerCase()))return"";return best2.name.slice(typed.length)},[input,popover,active]),open2=popover!==null&&popover.length>0;return{popover,cursor:active,setCursor,ghost,open:open2}}var import_react141=__toESM(require_react_production(),1);var exports_frecency={};__export(exports_frecency,{score:()=>score2,frecency:()=>exports_frecency,bump:()=>bump2,_reset:()=>_reset});import{join as join26}from"path";import{existsSync as existsSync27,readFileSync as readFileSync19,writeFileSync as writeFileSync9,appendFileSync,mkdirSync as mkdirSync7}from"fs";var MAX2=1000,file3=()=>join26(configDir(),"frecency.jsonl"),data2=null;function load6(){if(!existsSync27(file3()))return{};let rows3=readFileSync19(file3(),"utf-8").split(`
|
|
4205
|
+
`).filter(Boolean).map((l)=>{try{return JSON.parse(l)}catch{return null}}).filter((e)=>e!==null),latest2={};for(let e of rows3)latest2[e.path]=e;let kept=Object.values(latest2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);if(kept.length<rows3.length)mkdirSync7(configDir(),{recursive:!0}),writeFileSync9(file3(),kept.map((e)=>JSON.stringify(e)).join(`
|
|
4204
4206
|
`)+`
|
|
4205
|
-
`,"utf-8");return Object.fromEntries(kept.map((e)=>[e.path,e]))}function ensure2(){return data2??=load6()}function score2(p){let e=ensure2()[p];if(!e)return 0;let days=(Date.now()-e.at)/86400000;return e.n/(1+days)}function bump2(p){let d2=ensure2(),prev=d2[p],e={path:p,n:(prev?.n??0)+1,at:Date.now()};if(d2[p]=e,
|
|
4206
|
-
`,"utf-8"),Object.keys(d2).length>MAX2){let kept=Object.values(d2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);data2=Object.fromEntries(kept.map((x2)=>[x2.path,x2])),
|
|
4207
|
+
`,"utf-8");return Object.fromEntries(kept.map((e)=>[e.path,e]))}function ensure2(){return data2??=load6()}function score2(p){let e=ensure2()[p];if(!e)return 0;let days=(Date.now()-e.at)/86400000;return e.n/(1+days)}function bump2(p){let d2=ensure2(),prev=d2[p],e={path:p,n:(prev?.n??0)+1,at:Date.now()};if(d2[p]=e,mkdirSync7(configDir(),{recursive:!0}),appendFileSync(file3(),JSON.stringify(e)+`
|
|
4208
|
+
`,"utf-8"),Object.keys(d2).length>MAX2){let kept=Object.values(d2).sort((a,b2)=>b2.at-a.at).slice(0,MAX2);data2=Object.fromEntries(kept.map((x2)=>[x2.path,x2])),writeFileSync9(file3(),kept.map((x2)=>JSON.stringify(x2)).join(`
|
|
4207
4209
|
`)+`
|
|
4208
|
-
`,"utf-8")}}function _reset(){data2=null}var KEYWORDS=[{text:"@diff",display:"@diff",meta:"working-tree diff"},{text:"@staged",display:"@staged",meta:"staged changes"},{text:"@git:1",display:"@git:1",meta:"last 1 commit"},{text:"@git:3",display:"@git:3",meta:"last 3 commits"},{text:"@git:5",display:"@git:5",meta:"last 5 commits"},{text:"@url:",display:"@url:<\u2026>",meta:"fetch a URL"},{text:"@folder:",display:"@folder:<path>",meta:"recurse directory"}];function match3(word){let q5=word.toLowerCase();return KEYWORDS.filter((k2)=>k2.text.toLowerCase().startsWith(q5)&&k2.text!==word)}function atWordAt(input,cursor=input.length){if(input.startsWith("/"))return null;let i=cursor;while(i>0&&!/\s/.test(input[i-1]))i--;if(input[i]!=="@")return null;let j2=cursor;while(j2<input.length&&!/\s/.test(input[j2]))j2++;return{word:input.slice(i,j2),start:i}}function useAtRefPopover(input,cursor){let gw=useGateway(),ready=useGatewayReady(),[items,setItems]=import_react141.useState([]),[sel,setCursor]=import_react141.useState(0),seq=import_react141.useRef(0),dismissed=import_react141.useRef(null),spot=atWordAt(input,cursor);return import_react141.useEffect(()=>{if(!spot||!ready){setItems([]),setCursor(0);return}if(dismissed.current===spot.word)return;dismissed.current=null;let me2=++seq.current,fixed=match3(spot.word),t2=setTimeout(()=>{gw.request("complete.path",{word:spot.word}).then((r)=>{if(seq.current!==me2)return;let seen=new Set(fixed.map((k2)=>k2.text)),ranked=(r.items??[]).filter((i)=>!seen.has(i.text)).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems([...fixed,...ranked]),setCursor(0)}).catch(()=>{if(seq.current===me2)setItems(fixed),setCursor(0)})},120);return()=>clearTimeout(t2)},[spot?.word,ready,gw]),{open:spot!==null&&items.length>0,items,cursor:sel,setCursor,accept:(src3,idx2=sel,off)=>{let at=atWordAt(src3,off),it=items[idx2];if(!at||!it)return null;if(it.text.includes(":")&&!it.text.endsWith(":"))exports_frecency.bump(it.text);let trail2=it.text.endsWith(":")||it.text.endsWith("/")?"":" ";return src3.slice(0,at.start)+it.text+trail2+src3.slice(at.start+at.word.length)},dismiss:()=>{seq.current++,dismissed.current=spot?.word??null,setItems([])}}}var import_react142=__toESM(require_react_production(),1);var TAB_PATH_RE=/((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))[^\s]*)$/;function looksLikeSlashCommand(text4){return/^\/[^\s/]*(?:\s|$)/.test(text4)}function clear(setItems,setCursor,setReplace){setItems([]),setCursor(0),setReplace(0)}function completionRequest(input){let slash2=looksLikeSlashCommand(input),word=slash2?null:input.match(TAB_PATH_RE)?.[1]??null;if(!slash2&&!word)return null;if(slash2&&/^\/model(?:\s|$)/.test(input))return null;if(slash2)return{method:"complete.slash",params:{text:input},replaceFrom:1};return{method:"complete.path",params:{word},replaceFrom:input.length-word.length}}function acceptCompletion(input,item,replaceFrom){let replace=item.text.startsWith("/")&&input.startsWith("/")?0:replaceFrom,left=input.slice(0,replace);if(item.text.includes(":"))exports_frecency.bump(item.text);let space=item.text.endsWith("/")||/\s$/.test(item.text)?"":" ";return left+item.text+space}function useCompletion(input,blocked,gw){let[items,setItems]=import_react142.useState([]),[cursor,setCursor]=import_react142.useState(0),[replaceFrom,setReplace]=import_react142.useState(0),seq=import_react142.useRef(0),dismissed=import_react142.useRef(null);return import_react142.useEffect(()=>{if(blocked){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}let req=completionRequest(input);if(!req){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}if(dismissed.current===input)return;dismissed.current=null;let me2=++seq.current,t2=setTimeout(()=>{gw.request(req.method,req.params).then((r)=>{if(seq.current!==me2)return;let ranked=(r.items??[]).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems(ranked),setCursor(0),setReplace(req.method==="complete.slash"?r.replace_from??req.replaceFrom:req.replaceFrom)}).catch((e)=>{if(seq.current!==me2)return;setItems([{text:"",display:"completion unavailable",meta:e instanceof Error&&e.message?e.message:"unavailable"}]),setCursor(0),setReplace(req.replaceFrom)})},60);return()=>clearTimeout(t2)},[blocked,gw,input]),{open:items.length>0,items,cursor,setCursor,replaceFrom,dismiss:()=>{seq.current++,dismissed.current=input,clear(setItems,setCursor,setReplace)}}}var import_react143=__toESM(require_react_production(),1);import{join as join27}from"path";import{existsSync as
|
|
4209
|
-
`),parts:[]}}function safe2(s){try{return JSON.parse(s)}catch{return null}}function load7(){let FILE=file4();if(!
|
|
4210
|
-
`).filter(Boolean).map(parse5).slice(-MAX3).reverse()}function enc2(e){if(e.parts.length===0)return JSON.stringify({input:e.input});return JSON.stringify({input:e.input,parts:e.parts})}function useInputHistory(input,restore){let hist=import_react143.useRef(null);if(hist.current===null)hist.current=load7();let[,bump3]=import_react143.useState(0),idx2=import_react143.useRef(-1),stash=import_react143.useRef({input:"",parts:[]}),push3=import_react143.useCallback((entry2)=>{idx2.current=-1,stash.current={input:"",parts:[]};let e=typeof entry2==="string"?{input:entry2,parts:[]}:entry2;if(!e.input&&e.parts.length===0)return;let h2=hist.current,top=h2[0];if(top&&top.input===e.input&&sameParts(top.parts,e.parts))return;h2.unshift(e);let DIR=configDir(),FILE=file4();if(!
|
|
4210
|
+
`,"utf-8")}}function _reset(){data2=null}var KEYWORDS=[{text:"@diff",display:"@diff",meta:"working-tree diff"},{text:"@staged",display:"@staged",meta:"staged changes"},{text:"@git:1",display:"@git:1",meta:"last 1 commit"},{text:"@git:3",display:"@git:3",meta:"last 3 commits"},{text:"@git:5",display:"@git:5",meta:"last 5 commits"},{text:"@url:",display:"@url:<\u2026>",meta:"fetch a URL"},{text:"@folder:",display:"@folder:<path>",meta:"recurse directory"}];function match3(word){let q5=word.toLowerCase();return KEYWORDS.filter((k2)=>k2.text.toLowerCase().startsWith(q5)&&k2.text!==word)}function atWordAt(input,cursor=input.length){if(input.startsWith("/"))return null;let i=cursor;while(i>0&&!/\s/.test(input[i-1]))i--;if(input[i]!=="@")return null;let j2=cursor;while(j2<input.length&&!/\s/.test(input[j2]))j2++;return{word:input.slice(i,j2),start:i}}function useAtRefPopover(input,cursor){let gw=useGateway(),ready=useGatewayReady(),[items,setItems]=import_react141.useState([]),[sel,setCursor]=import_react141.useState(0),seq=import_react141.useRef(0),dismissed=import_react141.useRef(null),spot=atWordAt(input,cursor);return import_react141.useEffect(()=>{if(!spot||!ready){setItems([]),setCursor(0);return}if(dismissed.current===spot.word)return;dismissed.current=null;let me2=++seq.current,fixed=match3(spot.word),t2=setTimeout(()=>{gw.request("complete.path",{word:spot.word}).then((r)=>{if(seq.current!==me2)return;let seen=new Set(fixed.map((k2)=>k2.text)),ranked=(r.items??[]).filter((i)=>!seen.has(i.text)).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems([...fixed,...ranked]),setCursor(0)}).catch(()=>{if(seq.current===me2)setItems(fixed),setCursor(0)})},120);return()=>clearTimeout(t2)},[spot?.word,ready,gw]),{open:spot!==null&&items.length>0,items,cursor:sel,setCursor,accept:(src3,idx2=sel,off)=>{let at=atWordAt(src3,off),it=items[idx2];if(!at||!it)return null;if(it.text.includes(":")&&!it.text.endsWith(":"))exports_frecency.bump(it.text);let trail2=it.text.endsWith(":")||it.text.endsWith("/")?"":" ";return src3.slice(0,at.start)+it.text+trail2+src3.slice(at.start+at.word.length)},dismiss:()=>{seq.current++,dismissed.current=spot?.word??null,setItems([])}}}var import_react142=__toESM(require_react_production(),1);var TAB_PATH_RE=/((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))[^\s]*)$/;function looksLikeSlashCommand(text4){return/^\/[^\s/]*(?:\s|$)/.test(text4)}function clear(setItems,setCursor,setReplace){setItems([]),setCursor(0),setReplace(0)}function completionRequest(input){let slash2=looksLikeSlashCommand(input),word=slash2?null:input.match(TAB_PATH_RE)?.[1]??null;if(!slash2&&!word)return null;if(slash2&&/^\/model(?:\s|$)/.test(input))return null;if(slash2)return{method:"complete.slash",params:{text:input},replaceFrom:1};return{method:"complete.path",params:{word},replaceFrom:input.length-word.length}}function acceptCompletion(input,item,replaceFrom){let replace=item.text.startsWith("/")&&input.startsWith("/")?0:replaceFrom,left=input.slice(0,replace);if(item.text.includes(":"))exports_frecency.bump(item.text);let space=item.text.endsWith("/")||/\s$/.test(item.text)?"":" ";return left+item.text+space}function useCompletion(input,blocked,gw){let[items,setItems]=import_react142.useState([]),[cursor,setCursor]=import_react142.useState(0),[replaceFrom,setReplace]=import_react142.useState(0),seq=import_react142.useRef(0),dismissed=import_react142.useRef(null);return import_react142.useEffect(()=>{if(blocked){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}let req=completionRequest(input);if(!req){seq.current++,dismissed.current=null,clear(setItems,setCursor,setReplace);return}if(dismissed.current===input)return;dismissed.current=null;let me2=++seq.current,t2=setTimeout(()=>{gw.request(req.method,req.params).then((r)=>{if(seq.current!==me2)return;let ranked=(r.items??[]).map((i)=>({i,s:exports_frecency.score(i.text)})).sort((a,b2)=>b2.s-a.s).map((x2)=>x2.i);setItems(ranked),setCursor(0),setReplace(req.method==="complete.slash"?r.replace_from??req.replaceFrom:req.replaceFrom)}).catch((e)=>{if(seq.current!==me2)return;setItems([{text:"",display:"completion unavailable",meta:e instanceof Error&&e.message?e.message:"unavailable"}]),setCursor(0),setReplace(req.replaceFrom)})},60);return()=>clearTimeout(t2)},[blocked,gw,input]),{open:items.length>0,items,cursor,setCursor,replaceFrom,dismiss:()=>{seq.current++,dismissed.current=input,clear(setItems,setCursor,setReplace)}}}var import_react143=__toESM(require_react_production(),1);import{join as join27}from"path";import{existsSync as existsSync28,mkdirSync as mkdirSync8,readFileSync as readFileSync20,appendFileSync as appendFileSync2,writeFileSync as writeFileSync10}from"fs";var MAX3=500,file4=()=>join27(configDir(),"history");function parse5(line4){if(line4[0]==="{"){let j2=safe2(line4);if(j2&&typeof j2.input==="string")return{input:j2.input,parts:Array.isArray(j2.parts)?j2.parts:[]}}return{input:line4.replace(/\0/g,`
|
|
4211
|
+
`),parts:[]}}function safe2(s){try{return JSON.parse(s)}catch{return null}}function load7(){let FILE=file4();if(!existsSync28(FILE))return[];return readFileSync20(FILE,"utf-8").split(`
|
|
4212
|
+
`).filter(Boolean).map(parse5).slice(-MAX3).reverse()}function enc2(e){if(e.parts.length===0)return JSON.stringify({input:e.input});return JSON.stringify({input:e.input,parts:e.parts})}function useInputHistory(input,restore){let hist=import_react143.useRef(null);if(hist.current===null)hist.current=load7();let[,bump3]=import_react143.useState(0),idx2=import_react143.useRef(-1),stash=import_react143.useRef({input:"",parts:[]}),push3=import_react143.useCallback((entry2)=>{idx2.current=-1,stash.current={input:"",parts:[]};let e=typeof entry2==="string"?{input:entry2,parts:[]}:entry2;if(!e.input&&e.parts.length===0)return;let h2=hist.current,top=h2[0];if(top&&top.input===e.input&&sameParts(top.parts,e.parts))return;h2.unshift(e);let DIR=configDir(),FILE=file4();if(!existsSync28(DIR))mkdirSync8(DIR,{recursive:!0});if(h2.length>MAX3)h2.length=MAX3,writeFileSync10(FILE,[...h2].reverse().map(enc2).join(`
|
|
4211
4213
|
`)+`
|
|
4212
4214
|
`,"utf-8");else appendFileSync2(FILE,enc2(e)+`
|
|
4213
|
-
`,"utf-8");bump3((n)=>n+1)},[]),up=import_react143.useCallback(()=>{let h2=hist.current;if(h2.length===0)return;if(idx2.current===-1)stash.current={input,parts:[]};let next2=Math.min(idx2.current+1,h2.length-1);idx2.current=next2,restore(h2[next2])},[input,restore]),down=import_react143.useCallback(()=>{if(idx2.current===-1)return;let next2=idx2.current-1;idx2.current=next2,restore(next2===-1?stash.current:hist.current[next2])},[restore]);return{push:push3,up,down}}function sameParts(a,b2){if(a.length!==b2.length)return!1;for(let i=0;i<a.length;i++)if(a[i]?.type!==b2[i]?.type)return!1;return!0}var STYLE={file:"extmark.file",agent:"extmark.agent",paste:"extmark.paste"};function styles(syntax2,theme){let ensure3=(name,def2)=>{let id=syntax2.getStyleId(name);if(id!==null)return id;return syntax2.registerStyle(name,def2)};return{file:ensure3(STYLE.file,{fg:theme.accent}),agent:ensure3(STYLE.agent,{fg:theme.primary,italic:!0}),paste:ensure3(STYLE.paste,{fg:theme.textMuted})}}class PartsBuffer{ta;ex;typeId;style;list=[];map=new Map;constructor(ta,style){this.ta=ta,this.ex=ta.extmarks,this.style=style,this.typeId=this.ex.registerType("prompt-part")}text(){return this.ta.plainText}alive(){return!this.ta.isDestroyed}insertText(str4){if(!this.alive())return;this.ta.insertText(str4)}insertPart(part,virtualText){if(!this.alive())return;let start2=this.ta.visualCursor.offset,end=start2+visualLen(virtualText);this.ta.insertText(virtualText+" ");let id=this.ex.create({start:start2,end,virtual:!0,styleId:styleFor(part.type,this.style),typeId:this.typeId}),idx2=this.list.length;this.list.push(withSource(part,start2,end,virtualText)),this.map.set(id,idx2)}sync(){if(!this.alive())return;let alive=this.ex.getAllForTypeId(this.typeId),next2=[],nextMap=new Map;for(let m2 of alive){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(!p)continue;nextMap.set(m2.id,next2.length),next2.push(rangeTo(p,m2.start,m2.end))}this.list=next2,this.map=nextMap}parts(){return this.sync(),this.list}toSnapshot(){return{v:1,input:this.text(),parts:[...this.parts()]}}fromSnapshot(
|
|
4215
|
+
`,"utf-8");bump3((n)=>n+1)},[]),up=import_react143.useCallback(()=>{let h2=hist.current;if(h2.length===0)return;if(idx2.current===-1)stash.current={input,parts:[]};let next2=Math.min(idx2.current+1,h2.length-1);idx2.current=next2,restore(h2[next2])},[input,restore]),down=import_react143.useCallback(()=>{if(idx2.current===-1)return;let next2=idx2.current-1;idx2.current=next2,restore(next2===-1?stash.current:hist.current[next2])},[restore]);return{push:push3,up,down}}function sameParts(a,b2){if(a.length!==b2.length)return!1;for(let i=0;i<a.length;i++)if(a[i]?.type!==b2[i]?.type)return!1;return!0}var STYLE={file:"extmark.file",agent:"extmark.agent",paste:"extmark.paste"};function styles(syntax2,theme){let ensure3=(name,def2)=>{let id=syntax2.getStyleId(name);if(id!==null)return id;return syntax2.registerStyle(name,def2)};return{file:ensure3(STYLE.file,{fg:theme.accent}),agent:ensure3(STYLE.agent,{fg:theme.primary,italic:!0}),paste:ensure3(STYLE.paste,{fg:theme.textMuted})}}class PartsBuffer{ta;ex;typeId;style;list=[];map=new Map;constructor(ta,style){this.ta=ta,this.ex=ta.extmarks,this.style=style,this.typeId=this.ex.registerType("prompt-part")}text(){return this.ta.plainText}alive(){return!this.ta.isDestroyed}insertText(str4){if(!this.alive())return;this.ta.insertText(str4)}insertPart(part,virtualText){if(!this.alive())return;let start2=this.ta.visualCursor.offset,end=start2+visualLen(virtualText);this.ta.insertText(virtualText+" ");let id=this.ex.create({start:start2,end,virtual:!0,styleId:styleFor(part.type,this.style),typeId:this.typeId}),idx2=this.list.length;this.list.push(withSource(part,start2,end,virtualText)),this.map.set(id,idx2)}sync(){if(!this.alive())return;let alive=this.ex.getAllForTypeId(this.typeId),next2=[],nextMap=new Map;for(let m2 of alive){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(!p)continue;nextMap.set(m2.id,next2.length),next2.push(rangeTo(p,m2.start,m2.end))}this.list=next2,this.map=nextMap}parts(){return this.sync(),this.list}toSnapshot(){return{v:1,input:this.text(),parts:[...this.parts()]}}fromSnapshot(snap2){if(!this.alive())return;this.ta.setText(snap2.input),this.ex.clear(),this.list=[],this.map=new Map;for(let p of snap2.parts){let r=rangeOf(p);if(!r)continue;let id=this.ex.create({start:r.start,end:r.end,virtual:!0,styleId:styleFor(p.type,this.style),typeId:this.typeId});this.map.set(id,this.list.length),this.list.push(p)}this.ta.gotoBufferEnd()}clear(){if(this.list=[],this.map=new Map,!this.alive())return;this.ta.setText(""),this.ex.clear()}expand(){if(!this.alive())return{text:"",parts:[]};this.sync();let text4=this.text(),marks=this.ex.getAllForTypeId(this.typeId).sort((a,b2)=>b2.start-a.start);for(let m2 of marks){let idx2=this.map.get(m2.id);if(idx2===void 0)continue;let p=this.list[idx2];if(p?.type!=="text")continue;text4=text4.slice(0,m2.start)+p.text+text4.slice(m2.end)}return{text:text4,parts:this.list.filter((p)=>p.type!=="text")}}}function visualLen(s){let B3=globalThis.Bun;return B3?.stringWidth?B3.stringWidth(s):s.length}function styleFor(k2,s){if(k2==="file")return s.file;if(k2==="agent")return s.agent;return s.paste}function withSource(p,start2,end,value){if(p.type==="file")return{...p,source:p.source??{type:"file",path:"",text:{start:start2,end,value}}};if(p.type==="agent")return{...p,source:{start:start2,end,value}};return{...p,source:{text:{start:start2,end,value}}}}function rangeTo(p,start2,end){if(p.type==="file"){let src4=p.source??{type:"file",path:"",text:{start:start2,end,value:""}};return{...p,source:{...src4,text:{...src4.text,start:start2,end}}}}if(p.type==="agent"){let src4=p.source??{start:start2,end,value:""};return{...p,source:{...src4,start:start2,end}}}let src3=p.source??{text:{start:start2,end,value:""}};return{...p,source:{text:{...src3.text,start:start2,end}}}}function rangeOf(p){if(p.type==="file")return p.source?.text;if(p.type==="agent")return p.source;return p.source?.text}var import_react144=__toESM(require_react_production(),1);var MAX_VISIBLE=10;function badge2(source,theme){if(source==="skill")return theme.success;if(source==="plugin")return theme.info;if(source==="mcp")return theme.warning;return null}var SlashPopover=import_react144.memo(({commands:cmds,cursor,onCursor,onSelect})=>{let theme=useTheme().theme;if(cmds.length===0)return $jsx("box",{border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height:3,children:$jsx("text",{fg:theme.textMuted,children:"No matching commands"})});let rows3=import_react144.useMemo(()=>{let start3=Math.max(0,Math.min(cursor-2,cmds.length-MAX_VISIBLE)),items=cmds.slice(start3,start3+MAX_VISIBLE);return[{type:"header",cat:cmds[cursor]?.category??items[0]?.category??"Command"},...items.map((cmd,i)=>({type:"cmd",cmd,idx:start3+i}))]},[cmds,cursor]),start2=rows3.find((r)=>r.type==="cmd")?.idx??0,clipped=cmds.length>MAX_VISIBLE,above=clipped&&start2>0,below=clipped&&start2+MAX_VISIBLE<cmds.length,height=rows3.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,rows3.map((row4)=>{if(row4.type==="header")return $jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{children:$jsx("span",{fg:theme.textMuted,children:$jsx("strong",{children:row4.cat})})})},`h-${row4.cat}`);let active=row4.idx===cursor,color=badge2(row4.cmd.source,theme);return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(row4.idx),onMouseDown:()=>onSelect(row4.cmd),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,children:$jsxs("text",{children:[$jsxs("span",{fg:active?theme.primary:theme.text,children:["/",row4.cmd.name]}),row4.cmd.argsHint?$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.argsHint]}):null,$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.description]})]})}),$jsxs("box",{height:1,flexDirection:"row",children:[color?$jsx("text",{children:$jsxs("span",{fg:color,children:[" ",row4.cmd.source]})}):null,row4.cmd.keybind?$jsx("text",{children:$jsxs("span",{fg:theme.textMuted,children:[" ",row4.cmd.keybind]})}):null]})]},`c-${row4.idx}-${row4.cmd.name}`)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var import_react145=__toESM(require_react_production(),1);var MAX_VISIBLE2=10,AtRefPopover=import_react145.memo(({items,cursor,onCursor,onSelect})=>{let theme=useTheme().theme,start2=Math.max(0,Math.min(cursor-2,items.length-MAX_VISIBLE2)),visible2=items.slice(start2,start2+MAX_VISIBLE2),above=start2>0,below=start2+MAX_VISIBLE2<items.length,height=visible2.length+2+(above?1:0)+(below?1:0);return $jsxs("box",{flexDirection:"column",border:!0,borderStyle:"single",borderColor:theme.border,backgroundColor:theme.backgroundPanel,paddingX:1,height,children:[above?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2191 more"})}):null,visible2.map((it,j2)=>{let i=start2+j2,active=i===cursor;return $jsxs("box",{height:1,flexDirection:"row",backgroundColor:active?theme.backgroundElement:void 0,onMouseOver:()=>onCursor(i),onMouseDown:()=>onSelect(i),paddingLeft:2,paddingRight:1,children:[$jsx("box",{flexGrow:1,height:1,overflow:"hidden",children:$jsxs("text",{children:[$jsx("span",{fg:active?theme.primary:theme.text,children:it.display}),it.text!==it.display?$jsx("span",{fg:theme.textMuted,children:` ${it.text}`}):null]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:it.meta})})]},it.text)}),below?$jsx("box",{height:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:"\u2193 more"})}):null]})});var MAX_ROWS=6;function fmt5(n){if(n<1000)return String(n);if(n<1e6)return`${(n/1000).toFixed(1)}k`;return`${(n/1e6).toFixed(2)}M`}var Composer=import_react146.memo(import_react146.forwardRef((props,ref)=>{let theme=useTheme().theme,syntaxStyle=useTheme().syntaxStyle,gw=useGateway(),keys=useKeys(),bg2=useBackground(),ta=import_react146.useRef(null),buf=import_react146.useRef(null),sids=import_react146.useMemo(()=>styles(syntaxStyle,theme),[syntaxStyle,theme]),[input,setInput]=import_react146.useState(""),[caret,setCaret]=import_react146.useState(0),[mode,setMode]=import_react146.useState("normal"),modeRef=import_react146.useRef(mode);modeRef.current=mode;let head=import_react146.useMemo(()=>{let i=input.indexOf(`
|
|
4214
4216
|
`);return i<0?input:input.slice(0,i)},[input]),pop3=useSlashPopover(mode==="normal"?head:"",props.cmds),atSpot=mode==="normal"?atWordAt(input,caret):null,at=useAtRefPopover(mode==="normal"?input:"",caret),comp=useCompletion(mode==="normal"&&!atSpot?head:"",mode!=="normal"||pop3.open,gw),write=import_react146.useCallback((v2)=>{if(buf.current?.clear(),v2)ta.current?.setText(v2);ta.current?.gotoBufferEnd(),setInput(v2)},[]),restore=import_react146.useCallback((e)=>{if(e.parts.length===0){write(e.input);return}buf.current?.fromSnapshot({v:1,input:e.input,parts:[...e.parts]}),setInput(e.input)},[write]),hist=useInputHistory(input,restore),bindings=import_react146.useMemo(()=>[...toBindings(keys.chord("input.submit"),"submit"),...toBindings(keys.chord("input.newline"),"newline")],[keys]),live=import_react146.useRef({pop:pop3,at,comp,props,input});live.current={pop:pop3,at,comp,props,input};let wasDirty=import_react146.useRef(!1);import_react146.useEffect(()=>{let dirty2=input.trim().length>0;if(dirty2===wasDirty.current)return;wasDirty.current=dirty2,live.current.props.onDirty?.(dirty2)},[input]);let select2=(c)=>{if(c.name.includes(" ")){write(`/${c.name} `);return}write(""),live.current.props.onSlash(c)},atAccept=(idx2)=>{let off=ta.current?.cursorOffset,src3=live.current.input,which=idx2??live.current.at.cursor,it=live.current.at.items[which];if(!it)return;let a=atWordAt(src3,off),trail2=it.text.endsWith(":")||it.text.endsWith("/"),b2=buf.current;if(trail2||!b2||!ta.current||!a){let next2=live.current.at.accept(src3,idx2,off);if(next2!==null)write(next2);return}if(it.text.includes(":"))exports_frecency.bump(it.text);let eb=ta.current.editBuffer,s=eb.offsetToPosition(a.start),e=eb.offsetToPosition(a.start+a.word.length);if(!s||!e)return;ta.current.deleteRange(s.row,s.col,e.row,e.col),ta.current.cursorOffset=a.start;let part={type:"file",mime:"text/uri-list",filename:it.text,source:{type:"file",path:it.text,text:{start:a.start,end:a.start+it.text.length,value:it.text}}};b2.insertPart(part,it.text),setInput(ta.current.plainText)},paste=import_react146.useCallback((e)=>{e.preventDefault();let raw2=decodePasteBytes(e.bytes).replace(/\r\n?/g,`
|
|
4215
4217
|
`),text4=/[^\n]/.test(raw2)?raw2.replace(/\n+$/,""):raw2;if(!text4){live.current.props.onAttachClipboard?.();return}let verbatim=()=>ta.current?.insertText(text4);if(looksLikePath(text4)){gw.request("input.detect_drop",{text:text4}).then((r)=>{if(!r.matched)return verbatim();if(r.is_image){let{path:path7,count:count4,name,width,height,token_estimate}=r;if(live.current.props.onAttach?.({attached:!0,path:path7,count:count4,name,width,height,token_estimate}),!r.text.startsWith("[User attached"))ta.current?.insertText(r.text+" ");return}ta.current?.insertText(r.text+" ")}).catch(verbatim);return}if(text4.split(`
|
|
4216
4218
|
`).length<5)return verbatim();gw.request("paste.collapse",{text:text4}).then((r)=>ta.current?.insertText(r.placeholder+" ")).catch(verbatim)},[gw]),submit3=()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(!it||!it.text)return;write(acceptCompletion(live.current.input,it,cc.replaceFrom));return}let p=live.current.pop;if(p.open){let c=p.popover?.[p.cursor];if(c)select2(c);return}let exp=buf.current?.expand()??{text:live.current.input,parts:[]};if(modeRef.current==="shell"){let cmd=exp.text.trim();if(!cmd)return;hist.push({input:cmd,parts:exp.parts}),write(""),setMode("normal"),live.current.props.onShell?.(cmd);return}let text4=exp.text.trim();if(live.current.props.streaming){if(!text4||!live.current.props.canSubmitPrompt)return;if(hist.push({input:text4,parts:exp.parts}),write(""),text4.startsWith("/"))return void live.current.props.onSend(text4,exp.parts);live.current.props.onEnqueue?.(text4);return}let hasAtt=(live.current.props.attachments?.length??0)>0;if(!text4&&!hasAtt){live.current.props.onEmptyEnter?.();return}if(!live.current.props.canSubmitPrompt)return;if(text4)hist.push({input:text4,parts:exp.parts});write(""),live.current.props.onSend(text4,exp.parts)};import_react146.useImperativeHandle(ref,()=>({value:()=>live.current.input,set:write,insert:(text4)=>ta.current?.insertText(text4),remember:hist.push,lines:()=>ta.current?.lineCount??1,isEmpty:()=>live.current.input.trim().length===0,mode:()=>modeRef.current,setMode,caret:()=>ta.current?.cursorOffset??0,popOpen:()=>live.current.pop.open||live.current.at.open||live.current.comp.open,popNav:(d2)=>{let a=live.current.at;if(a.open)return a.setCursor((c)=>Math.max(0,Math.min(a.items.length-1,c+d2)));let cc=live.current.comp;if(cc.open)return cc.setCursor((c)=>Math.max(0,Math.min(cc.items.length-1,c+d2)));let max=(live.current.pop.popover?.length??1)-1;pop3.setCursor((c)=>Math.max(0,Math.min(max,c+d2)))},popAccept:()=>{if(live.current.at.open)return atAccept();let cc=live.current.comp;if(cc.open){let it=cc.items[cc.cursor];if(it?.text)write(acceptCompletion(live.current.input,it,cc.replaceFrom));return}let p=live.current.pop,c=p.popover?.[p.cursor];if(c)write(`/${c.name}${c.name.includes(" ")?" ":""}`)},popCancel:()=>{let a=live.current.at;if(a.open)return a.dismiss();let cc=live.current.comp;if(cc.open)return cc.dismiss();write("")},historyUp:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(t2.cursorOffset>0&&buf2.lastIndexOf(`
|
|
@@ -4218,10 +4220,10 @@ ${lines3.join(`
|
|
|
4218
4220
|
`)&&t2.cursorOffset!==0)return t2.cursorOffset=0,!0;return hist.up(),!0},historyDown:()=>{let t2=ta.current;if(!t2||modeRef.current==="shell")return!1;let buf2=live.current.input;if(buf2.indexOf(`
|
|
4219
4221
|
`,t2.cursorOffset)>=0)return!1;if(buf2.includes(`
|
|
4220
4222
|
`)&&t2.cursorOffset!==buf2.length)return t2.cursorOffset=buf2.length,!0;return hist.down(),!0}}),[hist.up,hist.down,pop3.setCursor,write]);let sidsRef=import_react146.useRef(sids);sidsRef.current=sids;let taRef=import_react146.useCallback((r)=>{if(ta.current=r,r&&!buf.current)buf.current=new PartsBuffer(r,sidsRef.current);if(!r)buf.current=null},[]),label2=!props.ready?"Connecting...":props.streaming?props.status||"Generating...":"Ready",dot=props.ready?props.streaming?theme.warning:theme.success:theme.error,rows3=Math.min(MAX_ROWS,Math.max(1,input.split(`
|
|
4221
|
-
`).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit3,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user)messages.push(...transcriptToMessages([{role:"user",text:user}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info2,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setSidebarPreview(void 0),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSidebarPreview(void 0),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[sidebarPreview,setSidebarPreview]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q5)=>[t2,...q5]);setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse});intr.current=stream.doInterrupt;let reset3=import_react152.useCallback(()=>{stream.interrupted.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset3(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset3,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset3(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset3(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset3(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset3,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash2=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info2,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash2(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
|
|
4223
|
+
`).length)),lift=rows3+3;return $jsxs("box",{flexDirection:"column",position:"relative",children:[props.focused&&pop3.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(SlashPopover,{commands:pop3.popover,cursor:pop3.cursor,onCursor:pop3.setCursor,onSelect:select2})}):props.focused&&at.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:at.items,cursor:at.cursor,onCursor:at.setCursor,onSelect:atAccept})}):props.focused&&comp.open?$jsx("box",{position:"absolute",bottom:lift,left:0,right:0,children:$jsx(AtRefPopover,{items:comp.items,cursor:comp.cursor,onCursor:comp.setCursor,onSelect:(idx2)=>{let it=comp.items[idx2];if(it?.text)write(acceptCompletion(input,it,comp.replaceFrom))}})}):null,(props.queue?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,children:props.queue.map((q5,i)=>$jsx("box",{height:1,onMouseDown:()=>props.onDequeue?.(i),children:$jsxs("text",{children:[$jsxs("span",{fg:theme.borderSubtle,children:[i===0?"\u256D":"\u2502"," "]}),$jsxs("span",{fg:theme.textMuted,children:["\u23F8 ",i+1,". ",trunc5(q5,60)]})]})},i))}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"column",paddingX:1,paddingBottom:1,gap:1,children:props.attachments.map((a)=>a.path?$jsx(ChafaImage,{path:a.path,width:60},`p-${a.path}`):null)}):null,(props.attachments?.length??0)>0?$jsx("box",{flexDirection:"row",flexWrap:"wrap",gap:1,paddingX:1,paddingBottom:1,children:props.attachments.map((a,i)=>$jsxs("text",{children:[$jsx("span",{bg:theme.accent,fg:theme.background,children:" img "}),$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[" ",a.name??`image ${i+1}`," "]}),a.width&&a.height?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:[a.width,"\xD7",a.height," "]}):null,a.token_estimate?$jsxs("span",{bg:theme.backgroundElement,fg:theme.textMuted,children:["~",fmt5(a.token_estimate),"t "]}):null,$jsx("span",{fg:theme.textMuted,children:" "}),$jsx("span",{fg:theme.textMuted,children:"\u232B to detach"})]},a.path??i))}):null,$jsxs("box",{border:!0,borderStyle:"single",borderColor:mode==="shell"?theme.primary:props.focused?theme.borderActive:theme.border,flexDirection:"row",position:"relative",children:[$jsx("box",{width:1,children:$jsx("text",{fg:theme.primary,children:mode==="shell"?"$":">"})}),$jsx("box",{width:1}),$jsx("textarea",{ref:taRef,syntaxStyle,onContentChange:()=>{let t2=ta.current;setInput(t2?.plainText??""),setCaret(t2?.cursorOffset??0)},onCursorChange:()=>{if(!live.current.input.includes("@"))return;let off=ta.current?.cursorOffset??0;setCaret((c)=>c===off?c:off)},onSubmit:submit3,onPaste:paste,keyBindings:bindings,wrapMode:"word",minHeight:1,maxHeight:MAX_ROWS,placeholder:mode==="shell"?"Run a shell command (30s cap, cwd) \u2014 esc or \u232B to exit":props.streaming?"Type to queue... (Enter queues, click chip to edit)":"Message Hermes... (/ for commands, Shift+Enter for newline)",focused:props.focused,textColor:theme.text,focusedTextColor:theme.text,placeholderColor:theme.textMuted,cursorColor:theme.text,backgroundColor:"transparent",focusedBackgroundColor:"transparent",flexGrow:1}),pop3.ghost&&props.focused&&rows3===1?$jsx("box",{position:"absolute",top:0,left:2+input.length,height:1,children:$jsx("text",{fg:theme.textMuted,children:pop3.ghost})}):null]}),$jsxs("box",{height:1,flexDirection:"row",paddingX:1,children:[$jsxs("text",{children:[$jsx("span",{fg:dot,children:"\u25CF "}),$jsx("span",{fg:theme.textMuted,children:mode==="shell"?"Shell":label2}),mode==="shell"?$jsx("span",{fg:theme.textMuted,children:" esc exit shell mode"}):props.streaming&&props.escHint?$jsx("span",{fg:theme.warning,children:" esc again to interrupt"}):props.streaming?$jsx("span",{fg:theme.textMuted,children:" esc\xD72 interrupt"}):null]}),$jsx("box",{flexGrow:1}),props.streaming&&(props.queue?.length??0)>0?$jsxs("text",{fg:theme.textMuted,children:[keys.print("queue.flush")," to send queued now "]}):null,bg2.count>0?$jsxs("text",{fg:theme.text,children:["\u25B6 ",bg2.count," "]}):null,props.model?$jsx("text",{fg:theme.textMuted,children:props.model}):null]})]})}));var import_react147=__toESM(require_react_production(),1);init_sessions_db();var normalize3=(sid2)=>sid2.trim().replace(/\.json$/i,"").replace(/^session_(?=\d{8}_)/,"");function useSession(){let gw=useGateway(),inflightMessages=(inflight)=>{let user=String(inflight?.user??"").trim(),assistant2=String(inflight?.assistant??""),messages=[];if(user)messages.push(...transcriptToMessages([{role:"user",text:user}]));if(assistant2||inflight?.streaming)messages.push(...transcriptToMessages([{role:"assistant",text:assistant2}]));return messages},resume=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.resume",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.resumed??target2);let messages=res.messages?.length?transcriptToMessages(res.messages):[];return{id,messages,info:res.info}},[gw]),create=import_react147.useCallback(async()=>{let res=await gw.request("session.create",{});return gw.setSession(res.session_id),{id:res.session_id,info:res.info}},[gw]),activate=import_react147.useCallback(async(sid2)=>{let target2=normalize3(sid2),res=await gw.request("session.activate",{session_id:target2}),id=res.session_id;gw.setSession(id),set("lastSessionId",res.session_key??id);let history=res.messages?.length?transcriptToMessages(res.messages):[],running2=Boolean(res.running||res.status==="working"||res.status==="waiting");return{id,info:res.info,messages:[...history,...inflightMessages(res.inflight)],running:running2,startedAt:res.started_at?res.started_at*1000:void 0,status:res.status}},[gw]),busy=import_react147.useCallback(async()=>{try{return(await gw.request("agents.list")).processes?.some((p)=>p.status==="running")??!1}catch{return!1}},[gw]),close=import_react147.useCallback(async(sid2,opts)=>{if(!sid2)return!1;if(opts?.preserveBackground&&await busy())return!1;try{return await gw.request("session.close",{session_id:sid2}),!0}catch{return!1}},[gw,busy]),boot2=import_react147.useCallback(async(launch)=>{let fresh2=async(note)=>({...await create(),messages:[],note});if(launch.mode==="resume"){let target2=launch.sid??exports_sessions_db.lastReal()?.id;if(!target2)return fresh2("no prior session to resume \u2014 starting fresh");try{return await resume(target2)}catch(e){let msg=e instanceof Error?e.message:String(e);return fresh2(`resume ${target2} failed: ${msg} \u2014 starting fresh`)}}let last3=get2("lastSessionId"),row4=last3?exports_sessions_db.byId(last3):null;if(row4?.message_count===0&&row4.parent_session_id==null)try{return await resume(row4.id)}catch{}return fresh2()},[create,resume]),interrupt=import_react147.useCallback(async()=>{try{await gw.request("session.interrupt")}catch{}},[gw]),branch2=import_react147.useCallback(async(name)=>{try{return(await gw.request("session.branch",name?{name}:{})).session_id??null}catch{return null}},[gw]),compress=import_react147.useCallback(async()=>{try{return await gw.request("session.compress")}catch{return null}},[gw]),undo=import_react147.useCallback(async()=>{try{await gw.request("session.undo")}catch{}},[gw]);return import_react147.useMemo(()=>({boot:boot2,create,resume,activate,close,interrupt,branch:branch2,compress,undo}),[boot2,create,resume,activate,close,interrupt,branch2,compress,undo])}init_sessions_db();init_hermes_analytics();function rehome(newHome){process.env.HERMES_HOME=newHome,setHome2(newHome),setHome(newHome),cache3.clear(),resetKanban(),exports_preferences.reload(),home2.reset()}var import_react148=__toESM(require_react_production(),1);var Countdown=(p)=>{let theme=useTheme().theme,[n,setN]=import_react148.useState(p.seconds);import_react148.useEffect(()=>{if(n<=0){p.onFire();return}let t2=setTimeout(()=>setN((v2)=>v2-1),1000);return()=>clearTimeout(t2)},[n,p.onFire]),useKeyboard(()=>p.onCancel());let bar3="\u2588".repeat(n)+"\u2591".repeat(Math.max(0,p.seconds-n));return $jsxs("box",{flexDirection:"column",width:58,children:[$jsx("box",{height:1,children:$jsx("text",{fg:theme.warning,children:$jsx("strong",{children:p.title})})}),$jsx("box",{height:1}),$jsx("box",{minHeight:1,children:$jsx("text",{wrapMode:"word",children:p.body})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsxs("text",{fg:theme.warning,children:[bar3," ",n,"s"]})}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:p.action})}),$jsx("box",{height:1}),$jsx("box",{height:1,children:$jsx("text",{fg:theme.textMuted,children:"press any key to cancel"})})]})};function openCountdown(dialog,opts){return new Promise((resolve4)=>{dialog.replace($jsx(Countdown,{...opts,onFire:()=>{dialog.clear(),resolve4(!0)},onCancel:()=>{dialog.clear(),resolve4(!1)}}),()=>resolve4(!1))})}var SECONDS=10,SUSPEND=process.platform==="darwin"?"pmset sleepnow":"systemctl suspend",run=(cmd)=>Bun.spawn(["sh","-c",cmd],{stdout:"ignore",stderr:"ignore"}),fired=new Map;function makeGoalHook(dialog,toast){let act=(goal,done2,total)=>{let pref=(exports_preferences.get("onGoalDone")??"toast").trim(),head=goal.length>60?goal.slice(0,57)+"\u2026":goal,n=total&&total>0?` ${done2}/${total} items`:"";if(toast.show({variant:"success",title:"Goal complete",message:head+n,duration:8000}),pref==="toast")return;let cmd=pref==="suspend"?SUSPEND:pref;openCountdown(dialog,{title:"Goal complete \u2014 "+(pref==="suspend"?"suspending":"running hook"),body:head,action:`\u2192 ${cmd}`,seconds:SECONDS}).then((ok)=>{if(ok)run(cmd)})};return{check:(sid2)=>{if(!sid2)return;io.goalState(sid2).then((s)=>{if(!s||s.status!=="done")return;if(fired.get(sid2)===s.goal)return;fired.set(sid2,s.goal);let list3=s.checklist??[],done2=list3.filter((i)=>i.status==="completed"||i.status==="impossible").length;act(s.goal,done2,list3.length)}).catch(()=>{})}}}var import_react150=__toESM(require_react_production(),1);function useVoice(gw,sys){let[enabled3,setEnabled]=import_react150.useState(!1),[recording,setRecording]=import_react150.useState(!1),[processing,setProcessing]=import_react150.useState(!1),[recordKeyRaw,setRecordKeyRaw]=import_react150.useState(),[tts,setTts]=import_react150.useState(!1),[onTranscript,setTranscript]=import_react150.useState(null),setOnTranscript=import_react150.useCallback((fn)=>setTranscript(fn?()=>fn:null),[]),recordKey=import_react150.useMemo(()=>parseVoiceRecordKey(recordKeyRaw),[recordKeyRaw]),keyLabel=import_react150.useMemo(()=>formatVoiceRecordKey(recordKey),[recordKey]),state2=import_react150.useMemo(()=>({enabled:enabled3,recording,processing,recordKey,tts}),[enabled3,recording,processing,recordKey,tts]),toggle=import_react150.useCallback(async(action,sid2)=>{try{let r=await gw("voice.toggle",{action,session_id:sid2});if(r.enabled!==void 0)setEnabled(r.enabled);if(r.tts!==void 0)setTts(r.tts);if(r.record_key)setRecordKeyRaw(r.record_key);let label2=formatVoiceRecordKey(parseVoiceRecordKey(r.record_key)),ttsMsg=r.tts?" \xB7 tts on":"";sys(`voice ${r.enabled?"on":"off"}${ttsMsg} [${label2}]`)}catch(e){sys(`voice: ${e instanceof Error?e.message:"gateway error"}`)}},[gw,sys]),record2=import_react150.useCallback(async(sid2)=>{if(!enabled3){sys("voice: mode is off \u2014 enable with /voice on");return}let starting=!recording,action=starting?"start":"stop";if(starting)setRecording(!0);else setRecording(!1),setProcessing(!1);try{let r=await gw("voice.record",{action,session_id:sid2});if(starting&&r.status!=="recording"){if(setRecording(!1),r.status==="busy")setProcessing(!0),sys("voice: still transcribing; try again shortly")}}catch(e){if(starting)setRecording(!1);sys(`voice error: ${e instanceof Error?e.message:"gateway error"}`)}},[enabled3,recording,gw,sys]);return{state:state2,toggle,record:record2,setEnabled,setRecording,setProcessing,setRecordKey:setRecordKeyRaw,keyLabel,onTranscript,setOnTranscript}}function VoiceIndicator({voice,keyLabel}){let theme=useTheme().theme;if(!voice.enabled&&!voice.recording&&!voice.processing)return null;let text4,fg2=theme.text;if(voice.recording)text4="\u25CF recording",fg2=theme.error;else if(voice.processing)text4="\u25CC transcribing",fg2=theme.warning;else text4=`voice ready [${keyLabel}]`,fg2=theme.textMuted;return $jsx("text",{children:$jsxs("span",{fg:fg2,children:[text4," "]})})}function sessionCapabilities(input){let sessionConnected=Boolean(input.sid),metadataHydrated=input.ready;return{sessionConnected,metadataHydrated,canSubmitPrompt:sessionConnected,canDispatchGatewayCommand:sessionConnected,canDrainQueue:sessionConnected&&!input.streaming}}var App=(props)=>$jsx(ThemeProvider,{initial:props.initialTheme,children:$jsx(GatewayProvider,{client:props.gateway,children:$jsx(ToastProvider,{children:$jsx(KeysProvider,{overrides:props.keyOverrides,children:$jsx(DialogProvider,{children:$jsx(CommandProvider,{children:$jsx(PluginProvider,{children:$jsx(BackgroundProvider,{children:$jsx(AppInner,{launch:props.launch??{mode:"new"}})})})})})})})})}),AppInner=({launch:launch0})=>{let gw=useGateway(),gwRestart=useGatewayRestart(),dialog=useDialog(),themeCtx=useTheme(),toast=useToast(),renderer=useRenderer(),plugins=usePlugins(),session=useSession(),dims=useTerminalDimensions(),goalHook=import_react152.useMemo(()=>makeGoalHook(dialog,toast),[dialog,toast]),[turn,dispatch]=import_react152.useReducer(turnReducer,initialTurn),[ready,setReady]=import_react152.useState(!1),[sid2,setSid]=import_react152.useState(""),sidRef=import_react152.useRef(sid2);sidRef.current=sid2;let capabilities=sessionCapabilities({sid:sid2,ready,streaming:turn.streaming}),[tab,setTab]=import_react152.useState(CHAT_TAB),[subTabs,setSubTabs]=import_react152.useState(()=>({[SESSIONS_TAB]:0,[AUTOMATION_TAB]:0,[CONFIG_TAB]:0,[EIKON_TAB]:0})),setSub=import_react152.useCallback((tabIdx,sub2)=>setSubTabs((prev)=>prev[tabIdx]===sub2?prev:{...prev,[tabIdx]:sub2}),[]),sessSub=import_react152.useCallback((i)=>setSub(SESSIONS_TAB,i),[setSub]),autoSub=import_react152.useCallback((i)=>setSub(AUTOMATION_TAB,i),[setSub]),cfgSub=import_react152.useCallback((i)=>setSub(CONFIG_TAB,i),[setSub]),eikSub=import_react152.useCallback((i)=>setSub(EIKON_TAB,i),[setSub]),[hideSidebar,setHideSidebar]=import_react152.useState(!1),[usage,setUsage]=import_react152.useState(void 0),[info2,setInfo]=import_react152.useState(null),[title,setTitle]=import_react152.useState(""),caption=title.trim(),titleRef=import_react152.useRef(caption);titleRef.current=caption,import_react152.useEffect(()=>{process.removeAllListeners("SIGINT"),process.on("SIGINT",()=>quit(renderer,sidRef.current,titleRef.current,gw))},[renderer,gw]),import_react152.useEffect(()=>{let w2=warning();if(!w2)return;toast.show({variant:"warning",title:"control server exposed",message:w2.message,duration:15000})},[toast]);let[focusRegion,setFocusRegion]=import_react152.useState("input"),goToTab=import_react152.useCallback((t2)=>{setTab(t2),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),goTo=import_react152.useCallback((t2,sub2)=>{setTab(t2),setSubTabs((prev)=>prev[t2]===sub2?prev:{...prev,[t2]:sub2}),setFocusRegion(t2===CHAT_TAB?"input":"content")},[]),[status,setStatus]=import_react152.useState(""),[escHint,setEscHint]=import_react152.useState(!1),[eikon,setEikon]=import_react152.useState(void 0),[queue,setQueue]=import_react152.useState([]),[busy,setBusy]=import_react152.useState("queue"),turnRef=import_react152.useRef(turn);turnRef.current=turn;let queueRef=import_react152.useRef(queue);queueRef.current=queue;let launchRef=import_react152.useRef(launch0),launch=launchRef.current,[splash,setSplash]=import_react152.useState(launch.splash!==!1),[switching,setSwitching]=import_react152.useState(!1),summoned=import_react152.useRef(!1),[composing,setComposing]=import_react152.useState(!1),splashLast=import_react152.useMemo(()=>launch.mode==="new"?lastReal():void 0,[launch.mode]),splashInfo=import_react152.useMemo(()=>info2?{agentVersion:info2.version,behind:info2.update_behind,model:info2.model}:void 0,[info2?.version,info2?.update_behind,info2?.model]),splashLastProp=import_react152.useMemo(()=>splashLast?{id:splashLast.id,title:splashLast.title}:void 0,[splashLast]),news=import_react152.useMemo(()=>readChangelog()?.headline,[]),[attachments,setAttachments]=import_react152.useState([]),[cloudH,setCloudH]=import_react152.useState(CLOUD_MIN),[pick2,setPick]=import_react152.useState(void 0),[skin,setSkin]=import_react152.useState(()=>deriveSkin(void 0)),inflight=import_react152.useRef(!1),undone=import_react152.useRef([]),sessionStart=import_react152.useRef(Date.now()),composer2=import_react152.useRef(null),promptRef=import_react152.useRef(null),{cmds}=useSlashCommands(),cmdsRef=import_react152.useRef(cmds);cmdsRef.current=cmds;let sys=import_react152.useCallback((text4)=>dispatch({kind:"system",text:text4}),[]),voice=useVoice(gw.request.bind(gw),sys);import_react152.useEffect(()=>{voice.setOnTranscript((text4)=>{let c=composer2.current;if(!c)return;c.set(""),setTimeout(()=>sendRef.current(text4),0)})},[]);let[errorPulse,setErrorPulse]=import_react152.useState(!1),agentState=errorPulse?"error":turn.toolActive?"working":turn.streaming&&turn.hasContent?"speaking":turn.streaming?"thinking":composing?"listening":"idle",onAvatarHold=import_react152.useCallback((s)=>{if(s==="error")setErrorPulse(!1)},[]),prompt=import_react152.useMemo(()=>pending2(turn.messages),[turn.messages]),cloudAuto=turn.streaming&&!turn.hasContent&&!prompt,[force,setForce]=import_react152.useState(void 0),cloud=!prompt&&(force??cloudAuto),prevStream=import_react152.useRef(turn.streaming);import_react152.useEffect(()=>{if(!prevStream.current&&turn.streaming)setForce(void 0),setPick(void 0);prevStream.current=turn.streaming},[turn.streaming]);let onPick=import_react152.useCallback((m2)=>{setPick((p)=>{if(m2&&p&&m2.id===p.id){setForce(!1);return}return setForce(!!m2),m2})},[]),onAvatar=import_react152.useCallback(()=>{let next2=!cloud;if(!next2)setPick(void 0);setForce(next2)},[cloud]),closeCloud=import_react152.useCallback(()=>{setForce(!1),setPick(void 0)},[]),intr=import_react152.useRef(()=>{}),steer=import_react152.useCallback((text4)=>{let v2=text4.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>toast.show(r.status==="queued"?{variant:"success",message:"Queued \u2014 lands on next tool result"}:{variant:"info",message:"No turn running; send as a normal message"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),openSteer=import_react152.useCallback(()=>{openTextPrompt(dialog,{title:"Steer active turn",label:"Soft nudge for the running session"}).then((v2)=>{if(v2)steer(v2)})},[dialog,steer]),onEnqueue=import_react152.useCallback((t2)=>{if(busy==="steer"){let v2=t2.trim();if(!v2)return;gw.request("session.steer",{text:v2}).then((r)=>{if(r.status==="queued")return toast.show({variant:"success",message:"Queued \u2014 lands on next tool result"});setQueue((q5)=>[...q5,t2]),toast.show({variant:"info",message:"steer rejected \u2014 queued for next turn"})}).catch(()=>setQueue((q5)=>[...q5,t2]));return}if(busy==="interrupt")return intr.current(),setQueue((q5)=>[t2,...q5]);setQueue((q5)=>[...q5,t2])},[busy,gw,toast]),onAttach=import_react152.useCallback((r)=>setAttachments((a)=>[...a,r]),[]),stream=useStream({dispatch,session,launchRef,sidRef,sessionStart,goalHook,setSid,setInfo,setReady,setTitle,setBusy,setUsage,setStatus,setSkin,setErrorPulse});intr.current=stream.doInterrupt;let reset3=import_react152.useCallback(()=>{stream.interrupted.current=!1,toast.clear("credits.depleted"),undone.current=[],dispatch({kind:"reset"}),setUsage(void 0),setReady(!1),setStatus(""),setTitle(""),setAttachments([])},[toast]),newSession=import_react152.useCallback(async()=>{let prev=sidRef.current;if(reset3(),summoned.current=!0,setSplash(!0),gw.setSession(""),setSid(""),prev)session.close(prev,{preserveBackground:!0});try{let r=await session.create();if(setSid(r.id),r.info)setInfo(r.info),setUsage(r.info.usage);sessionStart.current=Date.now()}catch{}},[reset3,session,gw]),switchSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.resume(target2);if(reset3(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(setReady(!0),sessionStart.current=Date.now(),res.messages.length)dispatch({kind:"load",messages:res.messages});if(prev&&prev!==res.id)session.close(prev,{preserveBackground:!0});setSplash(!1),summoned.current=!1}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to resume: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,gw]),liveStatus=(state2,running2=!1)=>{if(state2==="waiting")return"waiting for input\u2026";if(state2==="starting")return"starting agent\u2026";return running2||state2==="working"?"running\u2026":"ready"},activateSession=import_react152.useCallback(async(target2)=>{let prev=sidRef.current;summoned.current=!0,setSplash(!0),setSwitching(!0),gw.setSession(""),setSid(""),goToTab(CHAT_TAB);try{let res=await session.activate(target2);if(reset3(),setSid(res.id),res.info)setInfo(res.info),setUsage(res.info.usage);if(sessionStart.current=res.startedAt??Date.now(),dispatch({kind:"load.live",messages:res.messages,streaming:res.running}),setStatus(liveStatus(res.status,res.running)),setReady(!0),setSplash(!1),summoned.current=!1,prev&&prev!==res.id)toast.show({variant:"info",message:"switched live session"})}catch(err){if(prev)gw.setSession(prev),setSid(prev),setReady(!0);dispatch({kind:"system",text:`Failed to activate: ${err instanceof Error?err.message:String(err)}`}),setSplash(!1),summoned.current=!1}finally{setSwitching(!1)}},[reset3,session,goToTab,toast,gw]),switchProfile=import_react152.useCallback((newHome,name)=>{rehome(newHome),reset3(),gw.setSession(""),setSid(""),setInfo(null),setSkin(deriveSkin(void 0)),summoned.current=!0,setSplash(!0),launchRef.current={mode:"new",splash:!0},toast.show({variant:"info",message:`Switching to '${name}'\u2026`}),goToTab(CHAT_TAB),gwRestart()},[reset3,goToTab,gwRestart,toast,gw]),loadEikon=import_react152.useCallback((path7)=>{try{setEikon(parseEikonFile(path7))}catch{setEikon(void 0)}},[]),eikonName=usePref("eikon"),eikonRev=import_react152.useSyncExternalStore(exports_eikon.onRevision,exports_eikon.revision);import_react152.useEffect(()=>{let p=eikonName&&exports_eikon.baked(eikonName)||bundledEikonPath(skin.skin?.name);if(p)loadEikon(p);else setEikon(void 0)},[eikonName,eikonRev,skin.skin?.name,loadEikon]);let turnsFrom=(m2)=>{let msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);return at<0?0:msgs.slice(at).filter((x2)=>x2.role==="user").length},rewind=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2);if(n===0)return;let text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join("");for(let i=0;i<n;i++)await gw.request("session.undo").catch(()=>{});let r=await gw.request("session.history").catch(()=>null),msgs=turnRef.current.messages,at=msgs.findIndex((x2)=>x2.id===m2.id);dispatch({kind:"load",messages:r?transcriptToMessages(r.messages??[]):msgs.slice(0,at)}),composer2.current?.set(text4),setFocusRegion("input")},[gw]),fork2=import_react152.useCallback(async(m2)=>{if(turnRef.current.streaming)return;let n=turnsFrom(m2),text4=m2.parts.filter((p)=>p.type==="text").map((p)=>p.content).join(""),res=await gw.request("session.branch",{}).catch((e)=>{return toast.show({variant:"error",message:`branch failed: ${e.message}`}),null});if(!res?.session_id)return;for(let i=0;i<n;i++)await gw.request("session.undo",{session_id:res.session_id}).catch(()=>{});await activateSession(res.session_id),composer2.current?.set(text4),setFocusRegion("input"),toast.show({variant:"success",message:`forked \u2192 ${res.title??res.session_id}`})},[gw,toast,activateSession]),msgMenu=import_react152.useCallback((m2)=>{if(turnRef.current.streaming)return;openMessage(dialog,m2,{rewind,fork:fork2})},[dialog,rewind,fork2]),attachClipboard=import_react152.useCallback(()=>{gw.request("clipboard.paste").then((r)=>r.attached?setAttachments((a)=>[...a,r]):toast.show({variant:"info",message:r.message??"No image in clipboard"})).catch((e)=>toast.show({variant:"error",message:e.message}))},[gw,toast]),sendRef=import_react152.useRef(()=>{}),slash2=useSlash({dispatch,session,turnRef,queueRef,sendRef,composer:composer2,summoned,undone,capabilities,info:info2,sid:sid2,title:caption,skin,setQueue,setFocusRegion,setSplash,setAttachments,setInfo,setUsage,setTitle,newSession,switchSession,activateSession,rewind,goTo,attachClipboard,voiceToggle:voice.toggle}),send=import_react152.useCallback(async(raw2)=>{if(["exit","quit",":q",":q!",":wq"].includes(raw2.trim()))return quit(renderer,sidRef.current,titleRef.current,gw);let m2=raw2.match(/^\/(\S+)(?:\s+([\s\S]*))?$/);if(m2){let[,name,arg=""]=m2,r=resolve10(cmdsRef.current,name);if("hit"in r)return slash2(r.hit,arg.trim());if("ambiguous"in r){let head=r.ambiguous.slice(0,6).join(", ");return dispatch({kind:"system",text:`ambiguous: /${name} \u2192 ${head}${r.ambiguous.length>6?", \u2026":""}`})}}let text4=raw2;if(hasInterp(raw2))setStatus("interpolating\u2026"),text4=await interpolate(gw,raw2),setStatus("");stream.interrupted.current=!1;let withMedia=attachments.length?[...attachments.flatMap((a)=>a.path?[`MEDIA:${a.path}`]:[]),text4].filter(Boolean).join(`
|
|
4222
4224
|
`):text4;dispatch({kind:"user",text:withMedia}),setAttachments([]),undone.current=[],gw.request("prompt.submit",{text:text4}).catch(()=>{inflight.current=!1}),setTab(CHAT_TAB)},[gw,slash2,attachments]);sendRef.current=send;let onShell=import_react152.useCallback((command)=>{setSplash(!1),dispatch({kind:"system",text:`$ ${command}`}),setStatus("running\u2026"),gw.request("shell.exec",{command}).then((r)=>{let out=(r.stdout??"").trimEnd(),err=(r.stderr??"").trimEnd(),body2=[out,err&&`stderr:
|
|
4223
4225
|
${err}`].filter(Boolean).join(`
|
|
4224
|
-
`);if(dispatch({kind:"system",text:body2||`(exit ${r.code??0})`}),(r.code??0)!==0)toast.show({variant:"warning",message:`exit ${r.code}`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`})).finally(()=>setStatus(""))},[gw,toast]),onSend=import_react152.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react152.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react152.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react152.useEffect(()=>{if(!capabilities.canDrainQueue||inflight.current||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[capabilities.canDrainQueue,queue,send]);let dequeue=import_react152.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q5)=>q5.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),extra=plugins.routes,all2=import_react152.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react152.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react152.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;
|
|
4226
|
+
`);if(dispatch({kind:"system",text:body2||`(exit ${r.code??0})`}),(r.code??0)!==0)toast.show({variant:"warning",message:`exit ${r.code}`})}).catch((e)=>dispatch({kind:"system",text:`error: ${e.message}`})).finally(()=>setStatus(""))},[gw,toast]),onSend=import_react152.useCallback((raw2)=>{return setSplash(!1),send(raw2)},[send]),onEmptyEnter=import_react152.useCallback(()=>{if(!splash||summoned.current||!splashLast||composing)return!1;return setSplash(!1),switchSession(splashLast.id),!0},[splash,splashLast,composing,switchSession]);import_react152.useEffect(()=>{if(turn.streaming)inflight.current=!1},[turn.streaming]),import_react152.useEffect(()=>{if(!capabilities.canDrainQueue||inflight.current||queue.length===0)return;let[head,...rest]=queue;inflight.current=!0,setQueue(rest),send(head)},[capabilities.canDrainQueue,queue,send]);let dequeue=import_react152.useCallback((i)=>{let item=queueRef.current[i];if(item===void 0)return;setQueue((q5)=>q5.filter((_2,j2)=>j2!==i)),composer2.current?.set(item),setFocusRegion("input")},[]),extra=plugins.routes,all2=import_react152.useMemo(()=>[...TABS,...extra.map((r)=>({name:r.name,description:r.description??"Plugin"}))],[extra]),tabMax=all2.length-1;import_react152.useEffect(()=>{plugins.bind(goTo,()=>all2[tab]?.name)},[plugins,goTo,all2,tab]);let subCount=SUB_TABS[tab]?.length??0,cycleSub=import_react152.useCallback((dir2)=>{let labels=SUB_TABS[tab];if(!labels||labels.length===0)return;setSubTabs((prev)=>{let cur=prev[tab]??0,next2=(cur+dir2+labels.length)%labels.length;return next2===cur?prev:{...prev,[tab]:next2}})},[tab]);useAppKeys({tab,tabMax,chatTab:CHAT_TAB,setTab,subCount,cycleSub,focusRegion,setFocusRegion,streaming:turn.streaming,dialogOpen:dialog.open,composer:composer2,onPromptKey:(k2)=>promptRef.current?.feed(k2)??!1,onEscape:()=>{if(!splash||!summoned.current)return!1;return setSplash(!1),summoned.current=!1,!0},onInterrupt:stream.doInterrupt,queued:queue.length,onFlushQueue:stream.doInterrupt,onQuit:()=>quit(renderer,sid2,caption,gw),onQuitArm:(label2)=>toast.show({variant:"info",message:`${label2} again to quit`}),onInterruptNotice:()=>{setEscHint(!0),setTimeout(()=>setEscHint(!1),5000)},onCopyLast:()=>{let m2=[...turnRef.current.messages].reverse().find((x2)=>x2.role==="assistant"&&text(x2));if(m2)copy(text(m2))},onAttachClipboard:attachClipboard,onDetachLast:()=>{if(attachments.length===0)return!1;return setAttachments((a)=>a.slice(0,-1)),!0},onNotice:(text4)=>dispatch({kind:"system",text:text4}),onToggleSidebar:()=>setHideSidebar((v2)=>!v2),onSteer:openSteer,onStash:()=>{let c=composer2.current,v2=c?.value().trim()??"";if(!v2){let e=exports_stash.pop();if(!e)return toast.show({variant:"info",message:"stash empty"});c?.set(e.text);return}let n=exports_stash.push(v2);c?.set(""),toast.show({variant:"info",message:`stashed (${n})`})},voiceRecordKey:voice.state.recordKey,voiceEnabled:voice.state.enabled,onVoiceRecord:()=>voice.record(sidRef.current)}),useBridge({tab,ready,streaming:turn.streaming,messages:turn.messages,sid:sid2,focusRegion,setTab,setFocusRegion,dispatch,composer:composer2});let contentFocused=focusRegion==="content"&&!turn.streaming,promptAnswer=import_react152.useCallback((id,label2,ok)=>dispatch({kind:"prompt.answered",id,label:label2,ok}),[]),promptWire=import_react152.useMemo(()=>({ref:promptRef,onAnswer:promptAnswer}),[promptAnswer]);import_react152.useEffect(()=>{if(prompt&&tab!==CHAT_TAB)setTab(CHAT_TAB)},[prompt?.id]);let content=()=>{let inner=(()=>{switch(tab){case CHAT_TAB:return $jsx(Chat,{messages:turn.messages,streaming:turn.streaming,prompt:promptWire,cloud,cloudH,pick:pick2,onResize:setCloudH,onPick,onClose:closeCloud,onRewind:msgMenu});case SESSIONS_TAB:return $jsx(SessionsGroup,{focused:contentFocused,sub:subTabs[SESSIONS_TAB]??0,setSub:sessSub,onSwitch:switchSession,onActivateLive:activateSession,currentId:sid2,messages:turn.messages,sessionStart:sessionStart.current,info:info2??void 0,usage});case AUTOMATION_TAB:return $jsx(Automation,{focused:contentFocused,sub:subTabs[AUTOMATION_TAB]??0,setSub:autoSub,sessionId:sid2,onSwitchProfile:switchProfile});case CONFIG_TAB:return $jsx(ConfigGroup,{focused:contentFocused,sub:subTabs[CONFIG_TAB]??0,setSub:cfgSub});case EIKON_TAB:return $jsx(EikonGroup,{focused:contentFocused,sub:subTabs[EIKON_TAB]??0,setSub:eikSub});default:{let r=extra[tab-TABS.length];return r?r.render():null}}})(),name=all2[tab]?.name??"unknown";return $jsx(import_react152.Profiler,{id:`tab:${name}`,onRender,children:inner})},theme=themeCtx.theme,onMouseUp=import_react152.useCallback(()=>copySelection(renderer),[renderer]),inputFocused=focusRegion==="input"&&!prompt,sidebarVisible=dims.width>=(tab===CHAT_TAB?120:140)&&!hideSidebar;return $jsx(import_react152.Profiler,{id:"shell",onRender,children:$jsx(SkinProvider,{value:skin,children:$jsxs("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:theme.background,onMouseUp,children:[$jsx(TabBar,{tabs:all2,activeTab:tab,onTabChange:goToTab}),$jsxs("box",{flexGrow:1,flexDirection:"row",children:[$jsxs("box",{flexGrow:1,flexDirection:"column",children:[$jsxs("box",{flexGrow:1,position:"relative",children:[content(),splash&&tab===CHAT_TAB?$jsx(Splash,{info:splashInfo,last:summoned.current?void 0:splashLastProp,composing,news,loading:switching||!info2}):null]}),$jsxs("box",{flexShrink:0,zIndex:1,children:[$jsx(VoiceIndicator,{voice:voice.state,keyLabel:voice.keyLabel}),$jsx(Composer,{ref:composer2,focused:inputFocused,canSubmitPrompt:capabilities.canSubmitPrompt,ready,streaming:turn.streaming,status,model:info2?.model,escHint,queue,attachments,cmds,onSend,onSlash:slash2,onShell,onAttach,onAttachClipboard:attachClipboard,onEnqueue,onDequeue:dequeue,onDirty:setComposing,onEmptyEnter})]})]}),sidebarVisible?$jsx(import_react152.Profiler,{id:"sidebar",onRender,children:$jsx(Sidebar,{agentState,info:info2,usage,eikon,profile:activeProfileName(),title:caption,cloud:tab===0&&cloud,pulse:turn.streaming,onAvatar,onAvatarHold})}):null]}),plugins.has("app_bottom")?$jsx("box",{height:1,flexShrink:0,paddingX:1,overflow:"hidden",children:$jsx(plugins.Slot,{name:"app_bottom",mode:"single_winner",sid:sid2,tab,streaming:turn.streaming})}):null]})})})};var EIKON_CLI_USAGE=`herm eikon \u2014 install and manage Herm avatars
|
|
4225
4227
|
|
|
4226
4228
|
Usage:
|
|
4227
4229
|
herm eikon search [query] [--json]
|
|
@@ -4246,6 +4248,6 @@ Run 'herm eikon use ${out.name}' to activate.`)}if(cmd==="search"||cmd==="browse
|
|
|
4246
4248
|
installed: ${out.installed}`)}if(cmd==="info"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon info <name>",p.json);if(!deps.has(name))return emitError(io2,`No installed eikon named '${name}'`,p.json);let out=deps.info(name);if(p.json)return emit(io2,JSON.stringify({ok:!0,...out}));return emit(io2,`${out.name}${out.version?` v${out.version}`:""}${out.active?" active":" installed"}
|
|
4247
4249
|
source: ${out.source.kind} ${out.source.identity??out.source.origin??"unknown"}
|
|
4248
4250
|
trust: ${out.trust}`)}if(cmd==="list"){let rows3=deps.list().map((e)=>({name:e.name,file:e.file,hasSource:e.hasSource,sourceUrl:e.sourceUrl,lifecycle:e.lifecycle})),active=deps.getActive()??null;if(p.json)return emit(io2,JSON.stringify({ok:!0,active,eikons:rows3}));return emit(io2,rows3.length?rows3.map((e)=>`${e.name}${e.name===active?" *":""}`).join(`
|
|
4249
|
-
`):"No installed eikons")}if(cmd==="use"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon use <name>",p.json);if(!deps.has(name)&&!deps.baked(name))return emitError(io2,`No installed or bundled eikon named '${name}'`,p.json);if(deps.setActive(name),p.json)return emit(io2,JSON.stringify({ok:!0,active:name}));return emit(io2,`Avatar \u2192 ${name}`)}if(cmd==="remove"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon remove <name>",p.json);if(!deps.has(name))return emitError(io2,`No installed eikon named '${name}'`,p.json);let wasActive=deps.getActive()===name,result=deps.remove(name,{confirmActive:p.activeOk});if(result?.type==="active-consequence")return emitError(io2,activeMessage(result),p.json,{consequence:"active",action:result.action,name:result.name});if(p.json)return emit(io2,JSON.stringify({ok:!0,name,removed:!0,activeCleared:wasActive}));return emit(io2,`Removed '${name}'${wasActive?" and cleared active avatar":""}`)}if(cmd==="update"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon update <name>",p.json);let out=await deps.update(name,{confirmActive:p.activeOk});if(isActiveConsequence(out))return emitError(io2,activeMessage(out),p.json,{consequence:"active",action:out.action,name:out.name});let active=deps.getActive()??null;if(p.json)return emit(io2,JSON.stringify({ok:!0,name:out.name,n:out.n,bytes:out.bytes,active}));return emit(io2,`Updated '${out.name}' (${out.n} files)`)}return emitError(io2,`unknown eikon command '${cmd}'`,p.json)}catch(e){return emitError(io2,e instanceof Error?e.message:String(e),p.json)}}init_perf();var exports_bundled_skills={};__export(exports_bundled_skills,{sync:()=>sync,skills:()=>exports_bundled_skills});import{existsSync as
|
|
4250
|
-
`),js=doc.toJS();if(!js||typeof js!=="object"||Array.isArray(js))doc.contents=doc.createNode({});let cfg=obj2(doc.toJS()),plug=obj2(cfg.plugins);if(arr2(plug.disabled).includes(name)||arr2(plug.enabled).includes(name))return!1;return doc.setIn(["plugins","enabled"],[...arr2(plug.enabled),name]),
|
|
4251
|
+
`):"No installed eikons")}if(cmd==="use"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon use <name>",p.json);if(!deps.has(name)&&!deps.baked(name))return emitError(io2,`No installed or bundled eikon named '${name}'`,p.json);if(deps.setActive(name),p.json)return emit(io2,JSON.stringify({ok:!0,active:name}));return emit(io2,`Avatar \u2192 ${name}`)}if(cmd==="remove"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon remove <name>",p.json);if(!deps.has(name))return emitError(io2,`No installed eikon named '${name}'`,p.json);let wasActive=deps.getActive()===name,result=deps.remove(name,{confirmActive:p.activeOk});if(result?.type==="active-consequence")return emitError(io2,activeMessage(result),p.json,{consequence:"active",action:result.action,name:result.name});if(p.json)return emit(io2,JSON.stringify({ok:!0,name,removed:!0,activeCleared:wasActive}));return emit(io2,`Removed '${name}'${wasActive?" and cleared active avatar":""}`)}if(cmd==="update"){let name=p.values[0];if(!name)return emitError(io2,"usage: herm eikon update <name>",p.json);let out=await deps.update(name,{confirmActive:p.activeOk});if(isActiveConsequence(out))return emitError(io2,activeMessage(out),p.json,{consequence:"active",action:out.action,name:out.name});let active=deps.getActive()??null;if(p.json)return emit(io2,JSON.stringify({ok:!0,name:out.name,n:out.n,bytes:out.bytes,active}));return emit(io2,`Updated '${out.name}' (${out.n} files)`)}return emitError(io2,`unknown eikon command '${cmd}'`,p.json)}catch(e){return emitError(io2,e instanceof Error?e.message:String(e),p.json)}}init_perf();var exports_bundled_skills={};__export(exports_bundled_skills,{sync:()=>sync,skills:()=>exports_bundled_skills});import{existsSync as existsSync29,mkdirSync as mkdirSync9,readdirSync as readdirSync9,cpSync}from"fs";import{dirname as dirname16,join as join28}from"path";var locate4=()=>{let d2=import.meta.dir;for(let i=0;i<5;i++){let p=join28(d2,"assets/skills");if(existsSync29(p))return p;let up=dirname16(d2);if(up===d2)break;d2=up}return};function has(root2,n){if(existsSync29(join28(root2,n,"SKILL.md")))return!0;if(!existsSync29(root2))return!1;return readdirSync9(root2,{withFileTypes:!0}).some((e)=>e.isDirectory()&&existsSync29(join28(root2,e.name,n,"SKILL.md")))}function sync(){let src3=locate4();if(!src3)return[];let root2=hermesPath("skills"),dst=join28(root2,"creative"),out=[];for(let e of readdirSync9(src3,{withFileTypes:!0})){if(!e.isDirectory())continue;if(has(root2,e.name))continue;mkdirSync9(dst,{recursive:!0}),cpSync(join28(src3,e.name),join28(dst,e.name),{recursive:!0}),out.push(e.name)}return out}var exports_bundled_plugins={};__export(exports_bundled_plugins,{sync:()=>sync2,plugins:()=>exports_bundled_plugins});import{cpSync as cpSync2,existsSync as existsSync30,mkdirSync as mkdirSync10,readFileSync as readFileSync21,readdirSync as readdirSync10,writeFileSync as writeFileSync11}from"fs";import{dirname as dirname17,join as join29}from"path";var locate5=()=>{let dir2=import.meta.dir;for(let i=0;i<5;i++){let path7=join29(dir2,"assets/plugins");if(existsSync30(path7))return path7;let up=dirname17(dir2);if(up===dir2)break;dir2=up}return},obj2=(v2)=>v2&&typeof v2==="object"&&!Array.isArray(v2)?v2:{},arr2=(v2)=>Array.isArray(v2)?v2.map(String):[];function ours(dir2){let path7=join29(dir2,"plugin.yaml");if(!existsSync30(path7))return!1;let raw2=readFileSync21(path7,"utf8");return raw2.includes("name: eikon")&&raw2.includes("eikon_install")}function enable(name){let path7=hermesPath("config.yaml"),raw2=existsSync30(path7)?readFileSync21(path7,"utf8"):"",doc=$parseDocument(raw2||`{}
|
|
4252
|
+
`),js=doc.toJS();if(!js||typeof js!=="object"||Array.isArray(js))doc.contents=doc.createNode({});let cfg=obj2(doc.toJS()),plug=obj2(cfg.plugins);if(arr2(plug.disabled).includes(name)||arr2(plug.enabled).includes(name))return!1;return doc.setIn(["plugins","enabled"],[...arr2(plug.enabled),name]),mkdirSync10(dirname17(path7),{recursive:!0}),writeFileSync11(path7,String(doc),"utf8"),!0}function sync2(){let src3=locate5();if(!src3)return[];let root2=hermesPath("plugins"),out=[];for(let e of readdirSync10(src3,{withFileTypes:!0})){if(!e.isDirectory())continue;try{let dst=join29(root2,e.name),fresh2=!existsSync30(dst);if(fresh2)mkdirSync10(root2,{recursive:!0}),cpSync2(join29(src3,e.name),dst,{recursive:!0}),out.push(e.name);if(fresh2||ours(dst))enable(e.name)}catch{}}return out}import{writeSync as writeSync2}from"fs";var TERMINAL_MODE_RESET="\x1B[0'z\x1B[0'{\x1B[?2029l\x1B[?1016l\x1B[?1015l\x1B[?1006l\x1B[?1005l\x1B[?1003l\x1B[?1002l\x1B[?1001l\x1B[?1000l\x1B[?9l\x1B[?1004l\x1B[?2004l\x1B[?1049l\x1B[<u\x1B[>4;0m\x1B[0m\x1B[?25h";function resetTerminalModes(stream=process.stdout){if(!stream.isTTY)return!1;let fd=typeof stream.fd==="number"?stream.fd:stream===process.stdout?1:void 0;if(fd!==void 0)try{return writeSync2(fd,TERMINAL_MODE_RESET),!0}catch{}try{return stream.write(TERMINAL_MODE_RESET),!0}catch{return!1}}var wired=!1;function installExitResetHooks(){if(wired)return;wired=!0,process.on("exit",()=>{resetTerminalModes()});let codes={SIGHUP:129,SIGINT:130,SIGTERM:143};for(let sig of["SIGINT","SIGTERM","SIGHUP"])process.on(sig,()=>{resetTerminalModes(),process.exit(codes[sig])});process.on("uncaughtException",(err)=>{resetTerminalModes(),console.error(err),process.exit(1)}),process.on("unhandledRejection",(reason)=>{resetTerminalModes(),console.error(reason),process.exit(1)})}var cfg={columns:{fallback:80,max:500},rows:{fallback:24,max:200}};function sanitizeTerminalDimension(value,dim2){if(typeof value!=="number")return cfg[dim2].fallback;if(!Number.isFinite(value))return cfg[dim2].fallback;let n=Math.floor(value);if(n<2)return cfg[dim2].fallback;return Math.min(n,cfg[dim2].max)}function findDescriptor(stream,dim2){let cur=stream;while(cur){let desc=Object.getOwnPropertyDescriptor(cur,dim2);if(desc)return desc;cur=Object.getPrototypeOf(cur)}return}function patchDimension(stream,dim2){let desc=findDescriptor(stream,dim2);if(desc&&desc.configurable===!1)return!1;let raw2=desc&&"value"in desc?desc.value:void 0,read4=desc?.get,write=desc?.set;try{return Object.defineProperty(stream,dim2,{configurable:!0,enumerable:desc?.enumerable??!0,get(){let value=read4?read4.call(stream):raw2;return sanitizeTerminalDimension(value,dim2)},set(value){if(write){write.call(stream,value);return}raw2=value}}),!0}catch{return!1}}function clampStdoutDimensions(stream=process.stdout){if(!stream||typeof stream!=="object")return!1;let columns=patchDimension(stream,"columns"),rows3=patchDimension(stream,"rows");return columns||rows3}boot("import-graph",Bun.nanoseconds()/1e6);var argv=Bun.argv.slice(2);if(argv[0]==="eikon"&&argv[1]==="install")exports_bundled_plugins.sync();var eikonCliExit=await handleEikonCli(argv);if(eikonCliExit!==null)process.exit(eikonCliExit);if(argv.includes("--help")||argv.includes("-h"))process.stdout.write(HELP2),process.exit(0);if(argv.includes("--version")||argv.includes("-v"))process.stdout.write(VERSION+`
|
|
4251
4253
|
`),process.exit(0);var launch=parseLaunch(argv),main2=async()=>{resetTerminalModes(),installExitResetHooks(),clampStdoutDimensions(),mem("pre-renderer");let prefs=load2(),end=mark("renderer-init"),renderer=await createCliRenderer({exitOnCtrlC:!1,useMouse:prefs.mouse??!0,targetFps:prefs.targetFps??30,gatherStats:!1});end();let bump3=()=>renderer.capabilities?.kitty_keyboard||process.stdout.isTTY&&process.stdout.write("\x1B[>4;2m");bump3(),renderer.on("focus",bump3),mem("post-renderer"),await prime(prefs.theme??DEFAULT_THEME);let root2=createRoot(renderer),endRender=mark("first-render");root2.render($jsx(App,{initialTheme:prefs.theme,launch})),endRender(),boot("first-render",Bun.nanoseconds()/1e6),warmup(),warm(),exports_bundled_skills.sync(),exports_bundled_plugins.sync(),mem("post-first-render"),monitor(15000),start()};main2().catch(console.error);
|